Merge Two Sorted Lists

Pattern: Merging and sorting

easy

Keep a tail behind a dummy head. Repeatedly attach whichever front node is smaller and advance that list. When one list runs out, attach the rest of the other.

The problem

Given the heads of two sorted linked lists, merge them into one sorted list by relinking their nodes, and return its head. For example, 1 → 2 → 4 and 1 → 3 → 4 give 1 → 1 → 2 → 3 → 4 → 4. Either list may be empty.

The function name mergeTwoLists matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Which node comes first in the merged list?
  • After taking it, what is the next decision?
  • What happens when one list is used up?

Hints

    Brute force, and why it fails

    Copy all values into an array, sort, and build a new list: O((m + n) log(m + n)) and new nodes. Merging is O(m + n) and relinks the existing nodes.

    The key insight

    Two sorted lists only ever compete at their fronts. One comparison per node builds the whole merged list.

    Dry run

    list1 = 1 2 40 
    list2 = 1 3 41 
    merged

    list1 = 1 → 2 → 4 and list2 = 1 → 3 → 4. tail starts on a dummy.

    Step 1 of 4

    The plan

    dummy, tail = new node
    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 if list1 else list2
    return dummy.next
    

    Complexity

    Time
    O(m + n)
    Space
    O(1)

    Every node is attached once.

    Edge cases

    • Both empty: empty.
    • One empty: the other one.
    • Equal values: both are kept.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            ListNode dummy = new ListNode(0), tail = dummy;
            while (list1 != null && list2 != null) {
                if (list1.val <= list2.val) { tail.next = list1; list1 = list1.next; }   // take the smaller front
                else { tail.next = list2; list2 = list2.next; }
                tail = tail.next;
            }
            tail.next = list1 != null ? list1 : list2;   // the rest of whichever list is left
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
            ListNode dummy(0);
            ListNode* tail = &dummy;
            while (list1 != NULL && list2 != NULL) {
                if (list1->val <= list2->val) { tail->next = list1; list1 = list1->next; }   // take the smaller front
                else { tail->next = list2; list2 = list2->next; }
                tail = tail->next;
            }
            tail->next = list1 != NULL ? list1 : list2;  // the rest of whichever list is left
            return dummy.next;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
            dummy = tail = ListNode(0)
            while list1 is not None and list2 is not None:
                if list1.val <= list2.val:          # take the smaller front
                    tail.next, list1 = list1, list1.next
                else:
                    tail.next, list2 = list2, list2.next
                tail = tail.next
            tail.next = list1 if list1 is not None else list2   # the rest of whichever list is left
            return dummy.next

    Common mistakes

    • Forgetting to attach the leftover list.
    • Advancing tail before attaching.
    • Creating new nodes for every value instead of relinking.

    Similar problems