Merge Two Sorted Lists

EasyLinked listLeetCode 21 ↗World 1-8
0:00 / 0:00

Splice two sorted lists into one. Keep a tail pointer behind a dummy head and always take the smaller front node.

▼

The problem

LeetCode 21 (Easy). Given the heads of two sorted linked lists, splice their nodes together into one sorted list and return its head.

Example: list1 = [1,2,4], list2 = [1,3,4] → [1,1,2,3,4,4].

def mergeTwoLists(list1, list2):
    dummy = tail = ListNode()
    while list1 and list2:
        if list1.val <= list2.val:
            tail.next = list1
            list1 = list1.next
        else:
            tail.next = list2
            list2 = list2.next
        tail = tail.next
    tail.next = list1 or list2
    return dummy.next
TRY IT ON LEETCODE ▶

The solution

def mergeTwoLists(list1, list2):
    dummy = tail = ListNode()
    while list1 and list2:
        if list1.val <= list2.val:
            tail.next = list1
            list1 = list1.next
        else:
            tail.next = list2
            list2 = list2.next
        tail = tail.next
    tail.next = list1 or list2
    return dummy.next

Transcript

Merge Two Sorted Lists. You get the heads of two linked lists, each one already sorted. Splice their nodes together into one sorted list, and return its head.

For example, list one is one, two, four, and list two is one, three, four. Merged, that's one, one, two, three, four, four: six nodes, all in order. If either list is empty, the answer is just the other one.

The easy way: copy every value into an array, sort it, and build a brand new list. It works, but sorting costs n log n time, the copies take extra space, and it ignores that both lists were already sorted.

Here's the key. The smallest node left is always at the front of one of the lists. So compare the two fronts, take the smaller, and repeat, like a zipper closing one tooth at a time. A dummy node starts the merged list, and a tail pointer marks its end.

Let's zip the example. One and one tie, so list one's goes first. Then list two's one. Two beats three. Three beats four. Four and four tie, so list one's four. Now list one is empty: the loop stops, and the rest of list two, its last four, attaches in one step.

In code, dummy and tail start on one new node. While both lists have nodes, if list one's value is smaller or equal, attach it to the tail and advance list one. Otherwise, take from list two. Then the tail moves forward. After the loop, the tail takes whichever list is left, and we return the node after the dummy.

Each step attaches one node, so the time is order m plus n, where m and n are the two lengths. And we only move pointers, never copy nodes, so the extra space is constant.

Compare the fronts, take the smaller, attach the rest. That's Merge Two Sorted Lists.