Merge Sorted Array

easy

Merge two sorted arrays into first array in-place

Merge Sorted Array

Key Insight

Start from end to avoid overwriting. Compare and place larger element at back.

Step 1Setup
nums2=[2,5,6]
1
0
2
1
p1
p2
3
2
0
3
0
4
pos
0
5
converge

nums1=[1,2,3,0,0,0], nums2=[2,5,6]. Fill from end.

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Merge Sorted Array

Start from end to avoid overwriting. Compare and place larger element at back.

  1. Setup

    nums1=[1,2,3,0,0,0], nums2=[2,5,6]. Fill from end.

  2. Compare Ends

    3 vs 6. 6 is larger, place at position 5.

  3. Next Compare

    3 vs 5. 5 is larger, place at position 4.

  4. Continue

    3 vs 2. 3 is larger, place at position 3.

  5. Done

    Merged: [1, 2, 2, 3, 5, 6]