progress

~/problems / Two pointers

Merge Sorted Array

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Two sorted lists must become one, written into the first, which has exactly enough spare slots at the end.

Write merge_into(big: list[int], m: int, small: list[int], n: int) -> None. big holds m sorted values then n placeholder 0s; small holds n sorted values. Rearrange big in place so it holds all m + n values sorted.

big = [2, 5, 9, 0, 0]
merge_into(big, 3, [1, 6], 2)
big   # [1, 2, 5, 6, 9]

big = [0, 0]
merge_into(big, 0, [-3, 4], 2)
big   # [-3, 4]

m, n <= 10^5. Use O(1) extra space: no copies (the tests measure memory). ⭐ Bonus: a speed test earns a star in O(m + n).

Show hint

the back of big is empty. Which value belongs in the very last slot?

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc