Shuffle the Array — Solution in Python, Java & C++
Shuffle the Array solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays.
Shuffle the Array is an easy coding problem on arrays, asked in Amazon, Adobe and Wipro interviews.
- Difficulty: Easy
- Topics: Arrays
- Asked at: Amazon, Adobe, Wipro
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
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: x = [2,5,1] and y = [3,4,7], interleaved.
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 <= 20nums.length == 2n1 <= nums[i] <= 1000
Hints for Shuffle the Array
Hint 1
x_isits at indexiand its partnery_isits at indexi + n.Hint 2
One pass over
ifrom 0 to n - 1 appending both is all it takes.
How to solve Shuffle the Array
x_i lives at index i and y_i at index i + n; emit them alternately.
Approach
- For
iin0..n-1, appendnums[i]thennums[i + n].
Why it works
The input layout puts the two halves back to back, so a single index addresses both members of each pair.
Complexity
- Time —
O(n) - Space —
O(n) for the output
Pitfalls
- An in-place version packs two values per slot using bit shifts; only worth it if extra space is forbidden.
Reference solution
Python
def shuffle(nums, n):
out = []
for i in range(n):
out.append(nums[i])
out.append(nums[i + n])
return outJava
public static int[] shuffle(int[] nums, int n) {
int[] out = new int[2 * n];
for (int i = 0; i < n; i++) {
out[2 * i] = nums[i];
out[2 * i + 1] = nums[i + n];
}
return out;
}C++
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> out;
for (int i = 0; i < n; i++) {
out.push_back(nums[i]);
out.push_back(nums[i + n]);
}
return out;
}JavaScript
var shuffle = function(nums, n) {
const out = [];
for (let i = 0; i < n; i++) {
out.push(nums[i]);
out.push(nums[i + n]);
}
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays