← Practice
πŸ“– Linked listslinked-list-merge-sorted
LessonΒ·difficulty 3/5Β·~16 min

Linked lists: merge two sorted

Linked lists: merge two sorted

A linked list stores values in separate nodes, each pointing to the next. To merge two sorted linked lists you walk both at once, always splicing in whichever current node is smaller, then advancing that list's pointer. This is LeetCode #21.

We will practice the exact same idea on plain Python lists instead of real nodes. A real linked-list version would re-wire node.next pointers; here we just read from two lists with two indices and append to a result. The core move β€” "compare the two fronts, take the smaller, advance" β€” is identical.

python
i = j = 0
while i < len(a) and j < len(b):
    # take the smaller of a[i] / b[j], then step that index forward

Your task

Write merge_sorted(a, b) that merges two already-ascending lists into one ascending list.

python
merge_sorted([1, 2, 4], [1, 3, 4])   # [1, 1, 2, 3, 4, 4]
merge_sorted([], [0])                 # [0]
merge_sorted([], [])                  # []

Hint: keep an index into each list. While both still have items, append the smaller front value and advance that index. When one runs out, append the rest of the other.

Tests

  • interleaved
  • one empty
  • both empty
  • disjoint runs
  • second first (hidden)
  • negatives (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.