1470. Shuffle the Array - Explanation
Description
The array nums has exactly 2 * n elements. Split it into two halves of length n, preserving the order within each half. Return a new array that alternates between the halves: first the first element of the first half, then the first element of the second half, then the second element of each half, and so on.
Example 1:
Input: nums = [1,2,3,4]
n = 2
Output: [1,3,2,4]Explanation: The halves are [1,2] and [3,4]. Alternating their elements gives [1,3,2,4].
Example 2:
Input: nums = [8,9]
n = 1
Output: [8,9]Explanation: Each half has one element, so the output is [8,9].
Example 3:
Input: nums = [5,5,7,7,9,9]
n = 3
Output: [5,7,5,9,7,9]Explanation: The halves are [5,5,7] and [7,9,9]. Their successive pairs are (5,7), (5,9), and (7,9), giving [5,7,5,9,7,9].
Constraints:
1 <= n <= 500nums.length == 2 * n1 <= nums[i] <= 1000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Array Indexing - Calculating source and destination indices based on position formulas
- Bit Manipulation - Packing and unpacking multiple values in a single integer for in-place solutions
- Modular Arithmetic - Using multiplication and modulo to encode/decode values without overflow
1. Iteration (Extra Space)
Intuition
The array is given as [x1, x2, ..., xn, y1, y2, ..., yn] and we need to rearrange it to [x1, y1, x2, y2, ..., xn, yn]. The simplest approach is to iterate through the first half of the array and alternate between picking elements from the first half (x values at index i) and the second half (y values at index i + n). We build the result in a new array.
Algorithm
- Create an empty result array.
- Loop
ifrom0ton - 1:- Append
nums[i](the x value) to the result. - Append
nums[i + n](the corresponding y value) to the result.
- Append
- Return the result array.
Time & Space Complexity
- Time complexity:
- Space complexity: extra space.
2. Multiplication And Modulo
Intuition
To shuffle in-place without extra space, we can encode two values in a single array element. Since values are at most 1000, we pick a base M > 1000. For each position i in the result, we determine which original element belongs there and encode it by adding original_value * M to nums[i]. The original value is retrieved using nums[index] % M (since we have not yet divided), and the new value is stored in the upper part. After encoding all positions, we divide each element by M to extract the shuffled values.
Algorithm
- Choose
M = max(nums) + 1or a constant like1001. - For each index
ifrom0to2n - 1:- If
iis even, the value should come from positioni / 2(anxvalue). - If
iis odd, the value should come from positionn + i / 2(ayvalue). - Add
(nums[source] % M) * Mtonums[i].
- If
- Divide each element by
Mto get the final shuffled array. - Return the modified array.
Time & Space Complexity
- Time complexity:
- Space complexity: extra space.
3. Bit Manipulation
Intuition
Similar to the multiplication approach, we can use bit manipulation to pack two values into one integer. Since values fit in 10 bits (max 1000 < 1024 = 2^10), we can store one value in the lower 10 bits and another in the upper bits. First, we pack each x and its corresponding y into the first half of the array. Then we unpack them from back to front into their final interleaved positions, ensuring we do not overwrite values we still need.
Algorithm
- For each
ifrom0ton - 1:- Combine
nums[i](x) andnums[i + n](y) intonums[i]using:nums[i] = (nums[i] << 10) | nums[i + n].
- Combine
- Starting from
i = n - 1down to0, and using a pointerjstarting at2n - 1:- Extract
y = nums[i] & ((1 << 10) - 1). - Extract
x = nums[i] >> 10. - Place
nums[j] = yandnums[j - 1] = x. - Decrement
jby 2.
- Extract
- Return the modified array.
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
for i in range(n):
nums[i] = (nums[i] << 10) | nums[i + n] # Store x, y in nums[i]
j = 2 * n - 1
for i in range(n - 1, -1, -1):
y = nums[i] & ((1 << 10) - 1)
x = nums[i] >> 10
nums[j] = y
nums[j - 1] = x
j -= 2
return numsTime & Space Complexity
- Time complexity:
- Space complexity: extra space.
Common Pitfalls
Using Wrong Index for the Y Values
The array is structured as [x1, x2, ..., xn, y1, y2, ..., yn], where the y values start at index n, not index n-1. A common mistake is using nums[n + i - 1] instead of nums[n + i] when pairing x[i] with its corresponding y value, resulting in incorrect pairings.
Overwriting Values in In-Place Solutions
When attempting an in-place shuffle without extra space, a frequent error is overwriting values before they have been used. The bit manipulation and multiplication/modulo approaches carefully encode two values in one element to avoid this, but implementing them incorrectly (such as reading from a position after it has already been modified) corrupts the data and produces wrong results.
Sign in to join the discussion