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

  1. The first half of the array holds the x values and the second half holds the y values.
  2. For each index i in 0..n-1, the output takes nums[i] followed by nums[i + n].
  3. Appending in that order produces the required interleaving directly.
  4. A preallocated result array with res[2*i] and res[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 y values start at nums[n], so the offset is i + n.
  • Interleaving in the wrong order: each pair is (x_i, y_i), not (y_i, x_i).
  • Assuming n equals len(nums): n is 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.