Shuffle the Array
EASYDescription
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
Approaches
Checkout 2 different approaches to solve Shuffle the Array. Click on different approaches to view the approach and algorithm in detail.
Using an Extra Array
This approach involves creating a new array of the same size (2n) and filling it with elements from the input array in the desired shuffled order. It's the most straightforward and intuitive way to solve the problem.
Algorithm
- Create a new integer array
resultof size2n. - Iterate with an index
ifrom0ton-1. - For each
i, placenums[i](which isx_i) atresult[2*i]. - Place
nums[i+n](which isy_i) atresult[2*i + 1]. - Return the
resultarray.
The algorithm directly constructs the shuffled array by allocating new memory. It iterates through the first half of the input array (the x elements) and, for each x_i, it picks both x_i and its corresponding y_i and places them sequentially into the new result array.
For example, for i=0, it takes nums[0] (x₁) and nums[n] (y₁) and places them at result[0] and result[1]. For i=1, it takes nums[1] (x₂) and nums[n+1] (y₂) and places them at result[2] and result[3], and so on.
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;
}
}
Complexity Analysis
Pros and Cons
- Simple and easy to understand.
- The code is clean and readable.
- Not dependent on the constraints of the values in the array.
- Requires extra space proportional to the input size, which can be inefficient for very large arrays.
Code Solutions
Checking out 3 solutions in different languages for Shuffle the Array. Click on different languages to view the code.
class Solution { public int [] shuffle ( int [] nums , int n ) { int [] ans = new int [ n << 1 ]; for ( int i = 0 , j = 0 ; i < n ; ++ i ) { ans [ j ++] = nums [ i ]; ans [ j ++] = nums [ i + n ]; } return ans ; } }Video Solution
Watch the video walkthrough for Shuffle the Array
Similar Questions
5 related questions you might find useful
Data Structures:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.