Member-only story
This article refers to a problem from Leetcode (https://leetcode.com/problems/shuffle-the-array/).
Problem:
Given the array nums
consisting of 2n
elements in the form [x1,x2,...,xn,y1,y2,...,yn]
.
Return the array in the form [x1,y1,x2,y2,...,xn,yn]
.
Thoughts and solution:
First thought is we can create and push to a new array within a for
loop.
var shuffle = function(nums, n) {
let yIndex = n
let xIndex = 0
let array = []
for(let i = 0; i < n; i++){
array.push(nums[xIndex], nums[yIndex])
xIndex ++
yIndex ++
}
return array
};
Both the space and time complexity is O(n). Is there a way to minimize the space complexity?
If there were, it would probably be an in-place shuffle which would result in O(1) space.
Can you think of an in-place solution to the above problem? If so, let me know in the comments down below!