Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Merge Two Sorted Lists

EasyLeetCode 21 ↗

The problem, in one line. Given the heads of two sorted lists, splice their nodes into one sorted list and return its head. LeetCode 21.

The tell. Two sequences that are already in order and one ordered result wanted. When both inputs are sorted, only their two fronts can be the next answer.

The wrong first idea

Dump both lists into one array, sort it, and build a new list.

vals = sorted(to_list(a) + to_list(b))

It is correct, but sorting costs n log n for the combined length n, and it throws away the order both lists already had. Walking two sorted fronts costs n.

The invariant

Everything behind tail is final, and nothing left in either list is smaller than it. Each step moves the smaller front onto the end of the result:

a: 1 4 6    b: 2 3 7 8    out: (empty)
take 1      a: 4 6        out: 1
take 2      b: 3 7 8      out: 1 2
take 3      b: 7 8        out: 1 2 3
take 4, 6   a: empty      out: 1 2 3 4 6, then attach 7 8

The solution

class ListNode:
    def __init__(self, val=0, next=None): self.val, self.next = val, next
def build(a, h=None):
    for v in reversed(a): h = ListNode(v, h)
    return h
def to_list(h): return [h.val] + to_list(h.next) if h else []

def merge(a, b):
    dummy = tail = ListNode()
    while a and b:
        if a.val <= b.val: tail.next, a = a, a.next   # take the smaller front
        else: tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b     # one side is empty, the other is already sorted
    return dummy.next

print(to_list(merge(build([1, 4, 6]), build([2, 3, 7, 8]))))
print(to_list(merge(build([]), build([5]))))
print(to_list(merge(build([]), build([]))))
[1, 2, 3, 4, 6, 7, 8]
[5]
[]
func merge(a, b *ListNode) *ListNode {
	dummy := &ListNode{}
	tail := dummy
	for a != nil && b != nil {
		if a.Val <= b.Val { // take the smaller front
			tail.Next, a = a, a.Next
		} else {
			tail.Next, b = b, b.Next
		}
		tail = tail.Next
	}
	if a != nil { // one side is empty, the other is already sorted
		tail.Next = a
	} else {
		tail.Next = b
	}
	return dummy.Next
}

Go needs a ListNode struct with Val and Next, plus a build and a toSlice helper. The same calls then print [1 2 3 4 6 7 8], [5], [].

Complexity

  • Time O(m + n): each step moves one node and no node moves twice.
  • Space O(1): the nodes are relinked, not copied, and the dummy is one extra node.

Traps

  • Forgetting the leftover. Merging [5] with [1, 2, 3] gives [1, 2, 3] and drops the 5, because the loop stops when either side runs out.
  • Skipping the dummy node. The first node of the result then needs its own special case, and two empty lists need another.
  • Looping on a or b. The comparison reads .val of a list that has run out, so [1] with [] raises AttributeError.

Next in the ladder

Linked List Cycle stops rewiring and asks about the shape of the chain instead, using two pointers that move at different speeds.