We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Shuffle the Array

Number: 1580

Difficulty: Easy

Paid? No

Companies: Google, Bloomberg, Amazon, Microsoft, Yahoo, Apple, Uber


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.


Code Solutions

def shuffle(nums, n):
    # Create an empty list to store the result
    result = []
    # Loop through the first half of the array
    for i in range(n):
        # Append the element from the first half
        result.append(nums[i])
        # Append the corresponding element from the second half
        result.append(nums[i + n])
    return result

# Example usage:
# nums = [2,5,1,3,4,7]
# print(shuffle(nums, 3))
← Back to All Questions