Beyond Big O

Merge sorted sequences

Merge sorted sequences

Easy

Solution guide

Reveal solution guide — spoilers

Approach

  1. Allocate a fresh output sequence and maintain one forward cursor into each sorted input.
  2. While both cursors have values, append the smaller current value and advance only its cursor. When equal, either side may be chosen first, but advance just that side so both occurrences are eventually included.
  3. After one input is exhausted, append every remaining value from the other input in order. Do not concatenate and sort or change either input.

Why it works

Each cursor points to the smallest unconsumed value in its input. The smaller of those two values is therefore the smallest remaining value overall. Appending it preserves sorted output, and consuming each input position once preserves every duplicate count.

Complexity

O(a + b) time for input lengths a and b, with O(1) auxiliary space excluding the O(a + b) returned output. Both cursors move forward at most their input length.

Edge cases to check

  • Either input may be empty; both empty produce an empty result.
  • Equal values within and across inputs must all remain in the result.
  • Copy the unconsumed tail into the new result rather than modifying either input.
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…