Merge Two Sorted Lists, visualized step by step

Easy One of the Blind 75 interview problems (LeetCode 21). Technique: linked list. Solution in Python, explained at every step.

The problem

You get the heads of two linked lists, each sorted from smallest to largest. Splice their nodes into one sorted list and return its head. No new value nodes are needed: the existing nodes are relinked.

Example: 2 → 6 → 9 and 3 → 4 → 10 become 2 → 3 → 4 → 6 → 9 → 10.

List a: 2, 6, 9. List b: 3, 4, 10. Answer: 2, 3, 4, 6, 9, 10 in one list, each node marked a or b for the list it came from.
The letters under the answer say which list each node came from.

Try it yourself first: LeetCode 21 ↗. Then step through the solution below.

Brute force

Copy every value of both lists into an array, sort it, and build a new list from it. That is O((n + m) log(n + m)) time and O(n + m) extra space, and it throws away the fact that both lists are already sorted.

The key insight

The smallest value not yet merged is always at the front of one of the two lists. So compare just the two fronts, link the smaller one to the end of the result, and move on in that list.

A dummy node in front of the result means the first node needs no special case: there is always a tail to link to. When one list runs out, the rest of the other is already sorted and is linked on in one step.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Merge Two Sorted Lists, step by step

Python

class Node:    def __init__(self, val, next=None):        self.val, self.next = val, next def merge(a, b):    dummy = tail = Node(0)    while a and b:        if a.val <= b.val:            tail.next = a            a = a.next        else:            tail.next = b            b = b.next        tail = tail.next    tail.next = a or b    return dummy.next
All steps as text
  1. Two sorted lists: a is 2 → 6 → 9, and b is 3 → 4 → 10. They should become one sorted list.
  2. A dummy node starts the result: dummy and tail both refer to it, and tail marks the end.
  3. Compare the fronts: a has 2, b has 3. 2 is smaller, so it comes next.
  4. Link dummy to 2.
  5. Move a on to 6, and tail to 2.
  6. Compare the fronts: a has 6, b has 3. 3 is smaller, so it comes next.
  7. Link 2 to 3.
  8. Move b on to 4, and tail to 3.
  9. Compare the fronts: a has 6, b has 4. 4 is smaller, so it comes next.
  10. Link 3 to 4 (it already was).
  11. Move b on to 10, and tail to 4.
  12. Compare the fronts: a has 6, b has 10. 6 is smaller, so it comes next.
  13. Link 4 to 6.
  14. Move a on to 9, and tail to 6.
  15. Compare the fronts: a has 9, b has 10. 9 is smaller, so it comes next.
  16. Link 6 to 9 (it already was).
  17. Move a past its last node, to no node (∅), and tail to 9.
  18. List a is empty, so the rest of b, 10, is linked on in one step: 9 links to 10.
  19. Return dummy.next: 2, the head of the merged list.
  20. Laid out in one row: 2 → 3 → 4 → 6 → 9 → 10. Each node was linked once: O(n + m) time, O(1) extra space.
Merge Two Sorted Lists, step by step. Last step: Laid out in one row: 2 → 3 → 4 → 6 → 9 → 10. Each node was linked once: O(n + m) time, O(1) extra space.

Note

In C++ the dummy is usually a local variable, Node dummy(0);, and tail starts as its address, &dummy: nothing is allocated, and nothing has to be deleted. In Java and Python it is a small object that the garbage collector removes.

Complexity

ApproachTimeSpace
Brute force: copy into an array, sort, rebuildO((n + m) log(n + m))O(n + m)
RecursionO(n + m)O(n + m)
Dummy node and a tail, one pass this pageO(n + m)O(1)

n and m are the lengths of the two lists.

  • Time: O(n + m). Every turn of the loop links one node, and the rest of the other list is linked in one step.
  • Space: O(1). The nodes are relinked, not copied; only the dummy node and two variables are new.

Note

Merging can also be written as a recursion: the smaller front node, linked to the merge of everything after it. It is shorter, but every node adds a call on the stack, O(n + m) space, and in Python two lists of about a thousand nodes in all already hit the recursion limit.

Edge cases

  • One list is empty: the loop never runs, tail.next becomes the other list, and that list comes back as it was.
  • Both lists are empty: the function returns dummy.next, which is None.
  • Equal values, like 1 → 3 and 1 → 2: the test is <=, so the 1 from a goes first, then the 1 from b: 1 → 1 → 2 → 3.
  • One list runs out early, like 5 and 1 → 2 → 3 → 4: four turns take 1 to 4 from b; then b is empty, and the 5 is linked on in one step.

Try it: put Merge Two Sorted Lists together step by step

The blocks below are steps of Merge Two Sorted Lists in words, and two of them do not belong. Put the right ones in order and check: your algorithm runs on the example, 2 → 6 → 9 and 3 → 4 → 10, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Merge Two Sorted Lists together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

What about k sorted lists? This is Merge k Sorted Lists (LeetCode 23), another Blind 75 problem. Put the front node of every list into a min-heap keyed by value. Take the smallest, link it to the result, and push its next node in its place. The heap compares values only: push each node with its value and its list's number, so that two equal values never fall back to comparing the nodes themselves. With N nodes in all, that is O(N log k) time and O(k) space for the heap.

The data structure behind it

  • Linked list: nodes, links and why relinking a node is O(1), step by step.
  • Merge sort: the same merge of two sorted halves, as the heart of a sort.