Problem Description
Given an array of 2n elements in the form [x₁,x₂,...,xₙ,y₁,y₂,...,yₙ], return a new array in the form [x₁,y₁,x₂,y₂,...,xₙ,yₙ].
Key Insights
- The array is split into two halves: the first n elements and the last n elements.
- Each element from the first half pairs with the corresponding element in the second half.
- A single iteration from 0 to n-1 is sufficient to interleave the elements correctly.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
The solution involves iterating over the first half of the array and interleaving elements from both halves. Create an empty result array and for each index i from 0 to n-1, add nums[i] from the first half and nums[i+n] from the second half to the result array. This approach leverages a simple loop ensuring a linear time complexity while using extra space to store the final array.