Shuffle the Array
This problem can be easily solved by understanding the pattern in the reshuffling of elements.
Approach
- Create an empty result list.
- Iterate through the array, considering both elements at the current index
i
and at the corresponding indexi+n
. - Add these elements to the result list.
- Return the result list.
Here’s the code implementing this approach:
|
|
Example
Let’s take nums = [2,5,1,3,4,7], n = 3
as an example:
- Iterate over the first 3 elements, and for each element, add it and the corresponding element from the second half to the result.
- Result:
[2,3,5,4,1,7]
.
Complexity
This solution has a time complexity of O(n) and a space complexity of O(n), where n is the value given in the input.