Shuffle the Array

Easy Topics Company Tags

The array nums has exactly 2 * n elements. Split it into two halves of length n, preserving the order within each half. Return a new array that alternates between the halves: first the first element of the first half, then the first element of the second half, then the second element of each half, and so on.

Example 1:

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

Output: [1,3,2,4]

Explanation: The halves are [1,2] and [3,4]. Alternating their elements gives [1,3,2,4].

Example 2:

Input: nums = [8,9]
n = 1

Output: [8,9]

Explanation: Each half has one element, so the output is [8,9].

Example 3:

Input: nums = [5,5,7,7,9,9]
n = 3

Output: [5,7,5,9,7,9]

Explanation: The halves are [5,5,7] and [7,9,9]. Their successive pairs are (5,7), (5,9), and (7,9), giving [5,7,5,9,7,9].

Constraints:

  • 1 <= n <= 500
  • nums.length == 2 * n
  • 1 <= nums[i] <= 1000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.