DSA AnimatorREVISION VIDEOS
← Back to problems
New

Merge Sorted Array — LeetCode 88 video explanation

You get two sorted arrays, nums 1 and nums 2. nums 1 has extra empty space at the end, exactly big enough for nums 2. Merge nums 2 into nums 1, in place, so the result is sorted.

Loading videos…

DSA Animator › DSA Revision › Arrays › Merge Sorted Array

Key moments in the Merge Sorted Array video

0:03Problem0:15Example0:25Brute force0:35Key idea0:50Dry run1:13Code1:32Takeaway

What you will learn

Remember: when there is free space at the end, merge from the back. Stop when the second array is empty; anything left in the first is already in place. The video solves Merge Sorted Array (LeetCode 88, Easy) with the Two Pointers pattern from the Arrays topic, and you can replay every step in the interactive Merge Sorted Array animation.

Merge Sorted Array video transcript

Problem

You get two sorted arrays, nums 1 and nums 2. nums 1 has extra empty space at the end, exactly big enough for nums 2. Merge nums 2 into nums 1, in place, so the result is sorted.

Example

nums 1 is 1, 2, 3 followed by three empty slots, and nums 2 is 2, 5, 6. The merged result is 1, 2, 2, 3, 5, 6.

Brute force

Copying nums 2 into the empty slots and sorting costs O of n log n. Merging from the front would overwrite values in nums 1 before you have used them.

Key idea

Merge from the back instead, where the empty space is. Compare the largest remaining value of each array, and write the bigger one into the last free slot. Nothing gets overwritten, because the write position is always behind the values still to be read.

Dry run

Compare 3 and 6: 6 is bigger, so it goes to the last slot. Compare 3 and 5: 5 goes to the slot before it. Compare 3 and 2: now 3 is bigger, so 3 moves to slot 3. Compare 2 and 2: take the 2 from nums 2 for slot 2. nums 2 is used up, and the 1 and 2 left in nums 1 are already in place. The result is 1, 2, 2, 3, 5, 6.

Code

In code, set i to the last real value of nums 1, j to the end of nums 2, and k to the very end. While nums 2 still has values, compare the two candidates. Write the larger one at k, and move that pointer and k back. Each slot is written once, so it's O of m plus n time, and O of 1 extra space.

Takeaway

Remember: when there is free space at the end, merge from the back. Stop when the second array is empty; anything left in the first is already in place.

More Arrays revision videos

← All 185 DSA revision videos