Shuffle the Array solution and explanation
9 more videos on this problem
Shuffle the Array (Constant Space) - Leetcode 1470 - PythonNeetCodeIO · 10:15 · 25K views
Leetcode Shuffle the Array | O(1) spaceCoding Interview Prep · 10:21 · 11K views
Leetcode Solution - 1470 Shuffle the ArrayJohn Leonardo · 5:09 · 3K views
Shuffle the Array | #1470 | Leetcode | JAVA ✅ | English | Explanation ➕ Live Coding 🔥Vishwas aithal · 8:26 · 2K views
1470. Shuffle the Array | LeetCode | Bit ManipulationDeep Tech · 14:45 · 1K views
Leetcode 1470 Shuffle the Array (Java)TheAnalyticGuy · 3:02 · 1K views
LEETCODE SOLUTION 1470 | Shuffle the Array | Leetcode for BEGINNERS | EASY | JavascriptCodingForBeginners · 7:54 · 1K views
LeetCode 1470. Shuffle the Array Solution Explained - JavaAlgorithms and Data Structures Course · 7:05 · 947 views
1470. Shuffle the Array | LEETCODE EASYcode Explainer · 5:13 · 835 views
Shuffle the Array | Leetcode 1470 | Zero to FAANG DSA BootcampHAIL CODING · 6:27 · 804 views
The problem
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2]
Constraints:
1 <= n <= 500nums.length == 2n1 <= nums[i] <= 10^3
Approach overview
Problem Overview: You’re given an array nums of length 2n. The first half contains x1, x2, ..., xn and the second half contains y1, y2, ..., yn. The task is to rearrange it into [x1, y1, x2, y2, ..., xn, yn]. The key observation: elements from the first half and second half must be interleaved in order.
Approach 1: Two-Pointer Technique (O(n) time, O(n) space)
This is the most direct solution. Maintain two pointers: one starting at index 0 for the x elements and another at index n for the y elements. Iterate while building a new result array. On each step, append nums[i] followed by nums[j], then increment both pointers. The logic mirrors the required output structure, making it easy to reason about. The algorithm scans the array once, so the time complexity is O(n), and it uses an additional array of size 2n, giving O(n) space complexity. This approach relies only on sequential iteration over an array and is typically the cleanest implementation.
Approach 2: In-place Reordering (O(n) time, O(1) space)
If extra memory is restricted, the array can be shuffled in place. The trick is to encode two values into a single integer temporarily. Since each number fits within a known bound, store both the original value and the future value using modular arithmetic or bit manipulation. For example, pack the new value into the higher bits while preserving the old value in the lower bits, then decode the final array in a second pass. This method still processes the array in linear time O(n) but avoids allocating a separate result array, achieving O(1) auxiliary space. The approach relies on careful index mapping and works well when practicing in-place manipulation problems in arrays or encoding tricks using bit manipulation.
Recommended for interviews: Interviewers usually expect the Two-Pointer Technique. It clearly demonstrates that you recognize the structure of the input and can construct the result in linear time. The in-place encoding solution is a useful follow-up when asked to optimize space complexity. Showing both approaches signals strong understanding of two-pointer patterns and array transformations.
Approach 1: Two-Pointer Technique
This approach uses a two-pointer technique to shuffle the array. The first pointer starts at the beginning of the array and represents the x values. The second pointer starts at the middle of the array and represents the y values. By iterating over the array and adding elements from these two pointers alternately to a new list, we can achieve the desired shuffle.
def shuffle(nums, n):
result = []
for i in range(n):
result.append(nums[i])
result.append(nums[i + n])
return result
nums = [2, 5, 1, 3, 4, 7]
n = 3
print(shuffle(nums, n))import java.util.*;
public class ShuffleArray {
public static 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;
}
public static void main(String[] args) {
int[] nums = {2, 5, 1, 3, 4, 7};
int n = 3;
int[] result = shuffle(nums, n);
System.out.println(Arrays.toString(result));
}
}#include <iostream>
#include <vector>
std::vector<int> shuffle(const std::vector<int>& nums, int n) {
std::vector<int> result;
for (int i = 0; i < n; ++i) {
result.push_back(nums[i]);
result.push_back(nums[i + n]);
}
return result;
}
int main() {
std::vector<int> nums = {2, 5, 1, 3, 4, 7};
int n = 3;
std::vector<int> result = shuffle(nums, n);
for (int num : result) {
std::cout << num << " ";
}
return 0;
}function shuffle(nums, n) {
let result = [];
for (let i = 0; i < n; i++) {
result.push(nums[i]);
result.push(nums[i + n]);
}
return result;
}
let nums = [2, 5, 1, 3, 4, 7];
let n = 3;
console.log(shuffle(nums, n));#include <stdio.h>
void shuffle(int* nums, int n, int* result) {
int i, j = 0;
for (i = 0; i < n; i++) {
result[j++] = nums[i];
result[j++] = nums[i + n];
}
}
int main() {
int nums[] = {2, 5, 1, 3, 4, 7};
int n = 3;
int result[sizeof(nums)/sizeof(nums[0])];
shuffle(nums, n, result);
for (int i = 0; i < 2 * n; i++) {
printf("%d ", result[i]);
}
return 0;
}using System;
class Program {
static 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;
}
static void Main() {
int[] nums = {2, 5, 1, 3, 4, 7};
int n = 3;
int[] result = Shuffle(nums, n);
Console.WriteLine(string.Join(", ", result));
}
}This Python solution utilizes list to achieve the shuffled form by iterating from 0 to n and appending elements alternately from each half of the nums list.
Time Complexity: O(n), where n is half the length of the input list.
Space Complexity: O(n), for constructing the shuffled list (output).
Approach 2: In-place Reordering
An alternate approach is to reorder the array in-place without using additional space. However, given the elements might need to be accessed multiple times, a good understanding of index manipulation and mathematics is required. The complexity to deduce the correct indices for swapping can increase the difficulty.
def shuffleInPlace(nums, n):
for i in range(n, 2 * n):
y = nums[i]
j = i
while j > 2 * (i - n):
nums[j] = nums[j - 1]
j -= 1
nums[2 * (i - n)] = y
nums = [2, 5, 1, 3, 4, 7]
n = 3
shuffleInPlace(nums, n)
print(nums)import java.util.Arrays;
public class ShuffleInPlace {
public static void shuffle(int[] nums, int n) {
for (int i = n; i < 2 * n; i++) {
int y = nums[i];
for (int j = i; j > 2 * (i - n); j--) {
nums[j] = nums[j - 1];
}
nums[2 * (i - n)] = y;
}
}
public static void main(String[] args) {
int[] nums = {2, 5, 1, 3, 4, 7};
int n = 3;
shuffle(nums, n);
System.out.println(Arrays.toString(nums));
}
}#include <iostream>
#include <vector>
void shuffleInPlace(std::vector<int>& nums, int n) {
for (int i = n; i < 2 * n; i++) {
int y = nums[i];
int j = i;
while (j > 2 * (i - n)) {
nums[j] = nums[j - 1];
j--;
}
nums[j] = y;
}
}
int main() {
std::vector<int> nums = {2, 5, 1, 3, 4, 7};
int n = 3;
shuffleInPlace(nums, n);
for (int num : nums) {
std::cout << num << " ";
}
return 0;
}function shuffleInPlace(nums, n) {
for (let i = n; i < 2 * n; i++) {
const y = nums[i];
let j = i;
while (j > 2 * (i - n)) {
nums[j] = nums[j - 1];
j--;
}
nums[2 * (i - n)] = y;
}
}
let nums = [2, 5, 1, 3, 4, 7];
let n = 3;
shuffleInPlace(nums, n);
console.log(nums);#include <stdio.h>
void shuffleInPlace(int* nums, int n) {
int temp, j;
for (int i = n; i < 2 * n; i++) {
temp = nums[i];
for (j = i; j > 2 * (i - n); j -= 2) {
nums[j] = nums[j - 1];
}
nums[j] = temp;
}
}
int main() {
int nums[] = {2, 5, 1, 3, 4, 7};
int n = 3;
shuffleInPlace(nums, n);
for (int i = 0; i < 2 * n; i++) {
printf("%d ", nums[i]);
}
return 0;
}using System;
class Program {
static void ShuffleInPlace(int[] nums, int n) {
for (int i = n; i < 2 * n; i++) {
int y = nums[i];
for (int j = i; j > 2 * (i - n); j--) {
nums[j] = nums[j - 1];
}
nums[2 * (i - n)] = y;
}
}
static void Main() {
int[] nums = {2, 5, 1, 3, 4, 7};
int n = 3;
ShuffleInPlace(nums, n);
Console.WriteLine(string.Join(", ", nums));
}
}This Python example offers an approach to shuffle the array in place by dynamically adjusting each element's position without requiring additional memory.
Time Complexity: O(n^2), because of the shifts.
Space Complexity: O(1), due to in-place adjustments.
Approach 3: Simulation
We traverse the indices i in the range [0, n). Each time, we take nums[i] and nums[i+n] and place them sequentially into the answer array.
After the traversal is complete, we return the answer array.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array nums.
function shuffle(nums: number[], n: number): number[] {
const ans: number[] = [];
for (let i = 0; i < n; ++i) {
ans.push(nums[i], nums[i + n]);
}
return ans;
}func shuffle(nums []int, n int) (ans []int) {
for i := 0; i < n; i++ {
ans = append(ans, nums[i])
ans = append(ans, nums[i+n])
}
return
}impl Solution {
pub fn shuffle(nums: Vec<i32>, n: i32) -> Vec<i32> {
let n = n as usize;
let mut ans = Vec::new();
for i in 0..n {
ans.push(nums[i]);
ans.push(nums[i + n]);
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Two-Pointer Technique | Time Complexity: O(n), where n is half the length of the input list. |
| In-place Reordering | Time Complexity: O(n^2), because of the shifts. |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Two-Pointer Technique | O(n) | O(n) | Best general solution. Simple, readable, and ideal for interviews. |
| In-place Reordering (Encoding Trick) | O(n) | O(1) | Useful when memory is constrained or when asked for constant space optimization. |
Frequently asked questions
Is Shuffle the Array easy or hard?
Shuffle the Array is classified as an Easy problem on LeetCode with a very high acceptance rate. The task mainly checks whether you can recognize a simple indexing pattern and implement an O(n) array traversal.
Shuffle the Array Python/Java solution
In Python or Java, the typical implementation uses two pointers and a result array. Iterate i from 0 to n-1 and append nums[i] followed by nums[i+n]. The logic is identical across languages and runs in O(n) time.
How to solve Shuffle the Array in O(n)?
Iterate through the first half of the array while pairing elements with the second half. For every index i from 0 to n-1, append nums[i] and nums[i+n] to the result. This processes all elements exactly once, giving O(n) time complexity.
What is the best approach for Shuffle the Array?
The two-pointer technique is the best and most readable approach. Start one pointer at index 0 and another at index n, then append elements alternately to a new array. This runs in O(n) time with O(n) extra space and directly matches the required output structure.
Is Shuffle the Array asked at Google/Amazon/Meta?
Shuffle the Array is a common beginner-level array problem seen in coding practice and early interview rounds. Variations of array interleaving or index mapping appear in interviews at companies like Amazon and Meta when testing basic array manipulation skills.
What data structure is used in Shuffle the Array?
The problem primarily uses arrays. Most solutions rely on sequential traversal of the array, sometimes combined with the two-pointer pattern or bit/number encoding techniques for in-place transformations.
What is the time complexity of Shuffle the Array?
Both common solutions run in O(n) time because each element is processed once. The standard two-pointer solution uses O(n) extra space for the result array, while the in-place encoding method reduces auxiliary space to O(1).
