NeetCode #859LC-1470EasyBit Manipulation
← Back to All Problems#859 · #1470 · Shuffle the Array(重新排列数组)
📌 Problem Statement & Constraints
Given the array
nums consisting of 2n elements arranged as [x1, x2, ..., xn, y1, y2, ..., yn], return the array [x1, y1, x2, y2, ..., xn, yn]. Constraints: 1 <= n <= 500, nums.length == 2n, 1 <= nums[i] <= 10^3.💡 Core Algorithmic Approaches
- The first half of the array holds the
xvalues and the second half holds theyvalues. - For each index
iin0..n-1, the output takesnums[i]followed bynums[i + n]. - Appending in that order produces the required interleaving directly.
- A preallocated result array with
res[2*i]andres[2*i + 1]avoids the repeated appends if desired.
💻 Benchmark Python3 Implementation
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
res = []
for i in range(n):
res.append(nums[i]) # x_i
res.append(nums[i + n]) # y_i
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass over half the array.
💾 Space Complexity
O(n): the output array.
⚠️ Interview Pitfalls & Follow-ups
- Indexing the second half from 0: the
yvalues start atnums[n], so the offset isi + n. - Interleaving in the wrong order: each pair is
(x_i, y_i), not(y_i, x_i). - Assuming
nequalslen(nums):nis half the length; using the full length reads out of bounds. - Building the result with slicing tricks that are hard to read: the explicit loop is clearer and equally efficient.