Merge two sorted lists

Lesson 9.4 · Easy · Two heads · 6 min · by Vinay C

We'll cover the following

Merge two sorted lists into one sorted list. The first half of the row is list A, the second half is list B.

Watch it run

Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.

16 items · 17 steps
10
i31
62
93
144
185
226
277
j28
49
510
1011
1212
1913
2514
3015

1 ≤ 2. Take 1 from list A.

merged [1]

1 / 17

The idea

Complexity

TimeSpaceWhy
O(n + m)O(1)Each node is linked once; nodes are reused.

In Python

def merge(a, b):
    dummy = tail = ListNode()
    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

Summary: say it in the interview

  • Keep one pointer at the front of each list. Take the smaller front, advance that list, and repeat. When one list runs out, the rest of the other is already sorted.
  • Time O(n + m), space O(1). Each node is linked once; nodes are reused.