Shuffle the Array Problem
#1470
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1470.
Given the array nums consisting of 2n elements in the form [x_1,x_2,...,x_n,y_1,y_2,...,y_n].
Return the array in the form [x_1,y_1,x_2,y_2,...,x_n,y_n].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x_1=2, x_2=5, x_3=1, y_1=3, y_2=4, y_3=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
Solution
Approach: Interleave the Two Halves
The first half of nums holds x_1 ... x_n and the second half holds y_1 ... y_n, so x_i sits at index i - 1 and y_i at index n + i - 1. Build the answer by walking i from 0 to n - 1 and writing nums[i] to position 2i and nums[n + i] to position 2i + 1.
Complexity: O(n) time and O(n) space for the answer.
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
result = []
for i in range(n):
result.append(nums[i]) # x_(i+1) from the first half
result.append(nums[n + i]) # y_(i+1) from the second half
return result