Shuffle the Array

This problem can be easily solved by understanding the pattern in the reshuffling of elements.

Approach

  1. Create an empty result list.
  2. Iterate through the array, considering both elements at the current index i and at the corresponding index i+n.
  3. Add these elements to the result list.
  4. Return the result list.

Here’s the code implementing this approach:

1
2
3
4
5
6
7
class Solution:
    def shuffle(self, nums: List[int], n: int) -> List[int]:
        result = []
        for i in range(n):
            result.append(nums[i])
            result.append(nums[i + n])
        return result

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.