DSA AnimatorREVISION VIDEOS
← Back to problems
New

Shuffle the Array — LeetCode 1470 video explanation

The array has 2 n numbers: x 1 to x n, followed by y 1 to y n. Return them interleaved: x 1, y 1, x 2, y 2, and so on.

Loading videos…

DSA Animator › DSA Revision › Arrays › Shuffle the Array

Key moments in the Shuffle the Array video

0:03Problem0:14Example0:27Brute force0:34Key idea0:41Dry run0:56Code1:08Takeaway

What you will learn

Remember: the partner of index i in the second half is i plus n. Pair number i fills positions 2 i and 2 i plus 1. The video solves Shuffle the Array (LeetCode 1470, Easy) with the Basics pattern from the Arrays topic, and you can replay every step in the interactive Shuffle the Array animation.

Shuffle the Array video transcript

Problem

The array has 2 n numbers: x 1 to x n, followed by y 1 to y n. Return them interleaved: x 1, y 1, x 2, y 2, and so on.

Example

For 2, 5, 1, 3, 4, 7 with n equal to 3, the x values are 2, 5, 1 and the y values are 3, 4, 7. Interleaved, the answer is 2, 3, 5, 4, 1, 7.

Brute force

You could split the array into two lists, then merge them. But a single loop with the right indexes does it directly.

Key idea

The i-th pair is x at index i, and y at index i plus n. They go to positions 2 i, and 2 i plus 1.

Dry run

Pair 0 takes 2 from index 0, and 3 from index 3. Pair 1 takes 5 from index 1, and 4 from index 4. Pair 2 takes 1 from index 2, and 7 from index 5. The answer is 2, 3, 5, 4, 1, 7.

Code

In code, create an answer of size 2 n. Loop i from 0 to n. Write x at 2 i, and y, from i plus n, at 2 i plus 1. It's O of n time, and O of n space for the answer.

Takeaway

Remember: the partner of index i in the second half is i plus n. Pair number i fills positions 2 i and 2 i plus 1.

More Arrays revision videos

← All 185 DSA revision videos