Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1470. Shuffle the Array - Leetcode Solution

Code Implementation

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
      
class Solution {
public:
    vector<int> shuffle(vector<int>& nums, int n) {
        vector<int> result;
        for (int i = 0; i < n; ++i) {
            result.push_back(nums[i]);
            result.push_back(nums[i + n]);
        }
        return result;
    }
};
      
class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] result = new int[2 * n];
        for (int i = 0; i < n; i++) {
            result[2 * i] = nums[i];
            result[2 * i + 1] = nums[i + n];
        }
        return result;
    }
}
      
var shuffle = function(nums, n) {
    let result = [];
    for (let i = 0; i < n; i++) {
        result.push(nums[i]);
        result.push(nums[i + n]);
    }
    return result;
};
      

Problem Description

Given an array nums consisting of 2n elements in the form [x1, x2, ..., xn, y1, y2, ..., yn], your task is to return a new array in the form [x1, y1, x2, y2, ..., xn, yn]. In other words, you must "shuffle" the array by interleaving the first n elements with the last n elements.

  • Each element from the first half (xs) and the second half (ys) must appear exactly once in the output.
  • Do not reuse or skip any elements.
  • There is always exactly one valid solution.
  • The value n is guaranteed to be such that 2n equals the length of nums.

Thought Process

To solve this problem, let's first understand what is being asked: we are given an array split into two equal halves. We need to create a new array by alternating elements from the first half and the second half. For each index i from 0 to n-1, we want to take nums[i] (from the first half) and nums[i + n] (from the second half) and place them in order in the new array.

The brute-force way to do this would be to create a new array and, for each index, append both elements from the two halves in sequence. Since we know the exact positions from where to pick the elements, we do not need to search or use any extra data structures.

Optimizing further, we can directly build the result in a single pass through the first half of the array. This is both time and space efficient, and avoids unnecessary complexity.

Solution Approach

Let's break down the solution step by step:

  1. Initialize an empty result array: This will store our shuffled output.
  2. Loop from 0 to n - 1: For each index i, do the following:
    • Append nums[i] to the result (element from the first half).
    • Append nums[i + n] to the result (element from the second half).
  3. Return the result array: Once the loop is done, the result array will have the desired interleaved order.

This approach is efficient because:

  • We only loop through the array once (O(n) time).
  • We use only one extra array of size 2n (O(n) space).
  • No complicated data structures or algorithms are needed, making it easy to implement and understand.

Example Walkthrough

Let's take an example to see how the algorithm works:

Input: nums = [2, 5, 1, 3, 4, 7], n = 3

The first half is [2, 5, 1] and the second half is [3, 4, 7].

  • Iteration 0: Append 2 (nums[0]), then 3 (nums[3]) → [2, 3]
  • Iteration 1: Append 5 (nums[1]), then 4 (nums[4]) → [2, 3, 5, 4]
  • Iteration 2: Append 1 (nums[2]), then 7 (nums[5]) → [2, 3, 5, 4, 1, 7]

Output: [2, 3, 5, 4, 1, 7]

At each step, we alternate between the two halves, ensuring all elements are included in the correct order.

Time and Space Complexity

  • Brute-force Approach:
    • Time Complexity: O(n), since we process each pair once.
    • Space Complexity: O(n), for the result array.
  • Optimized Approach (as above):
    • Time Complexity: O(n), for a single pass through the halves.
    • Space Complexity: O(n), due to the output array.

There is no way to reduce the space complexity below O(n) unless we are allowed to modify the input array in place and return it, but the problem expects a new array as output.

Summary

The "Shuffle the Array" problem is a straightforward exercise in array manipulation. By recognizing the structure of the input array and the pattern required for the output, we can design an efficient and simple solution that interleaves the two halves in a single pass. This approach is both intuitive and optimal for the given constraints, making it a great example of clean, readable code that leverages the properties of the problem.