Merge Sorted Array

Easy
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Merge Sorted Array

Approach

Merge from the end to avoid overwriting elements in nums1. Use three pointers: one at the end of valid elements in nums1, one at the end of nums2, and one at the last position of nums1. Place the larger element at the insert position and decrement the corresponding pointer.

Complexity Analysis

Time
O(m + n)
Space
O(1)

Pattern

Two Pointers (Converging from End)

Why It Works

Starting from the back ensures we never overwrite unprocessed nums1 elements, since the merged position is always at or beyond the current nums1 read position.

Updated Feb 2026