Skip to content

visual walkthrough

Merge Sorted Array

EasyMerge from the BackReported at: MetaMicrosoftApple+5

Filling from the end avoids overwriting data; a standard in-place merge.

Solve on LeetCode

The idea

nums1 already has spare room at its end. If you fill it from the back with the largest values first, you never overwrite a value you still need.

Compare the last unplaced value of each list, drop the bigger one into the last free slot, and walk backwards.

Complexity

approachtimespace
Merge into a new arrayO(m + n)O(m + n)
Merge from the backO(m + n)O(1)

More walkthroughs