Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in Python: Dummy Node and Splicing

Practice O(n + m) Read the full explanation

You get list1 and list2, the heads of two sorted linked lists.

Merge them into one sorted list, and return its head.

Use the nodes you already have. Change their next links to form one chain, and don't make new nodes.

Either list can be empty (its head is None). Both can be empty too.

 

Example 1:

Input: list1 = [2,6,7], list2 = [3,6,10,11]
Output: [2,3,6,6,7,10,11]
Explanation: Both lists have a 6.
The 6 from list1 goes first.
After the 7, list1 has no nodes left.
The rest of list2, 10 -> 11, goes at the end as it is.

Example 2:

Input: list1 = [5,9], list2 = []
Output: [5,9]
Explanation: The second list is empty.
So the answer is list1, unchanged.

Example 3:

Input: list1 = [-8,-1], list2 = [-5,4,4]
Output: [-8,-5,-1,4,4]
Explanation: Negative values and repeats work the same way.
The result is -8, -5, -1, then 4 -> 4.

 

Constraints:

  • Each list has 0 to 10,000 nodes.
  • Each value is from -100,000 to 100,000.
  • Both lists are in ascending order.
  • A value can repeat.

Note:

Your algorithm should run in O(n + m) time and use O(1) extra space, where n and m are the lengths of list1 and list2: it only re-links the nodes that are already there.

Start the merged list with a dummy node, an extra node before the first real node. Then the first node needs no special case. Every node is attached after the merged list's last node in the same way. The answer is the node after the dummy.

Merge the lists in a loop. A recursive merge goes one call deeper for every node. With 2 × 104 nodes, it can run out of call stack.

STEP 1 OF 11
    Ctrl + Enter to check

    PYTHON · LINKED LISTS

    Merge Two Sorted Lists in Python, explained

    Problem overview

    The method mergeTwoLists receives list1 and list2, the heads of two singly linked lists that are each sorted in ascending order. It must return the head of one sorted list that contains all the nodes of both. The nodes are spliced together: the existing nodes are re-linked, and no new ones are created for the result. Either list can be empty, or both, and the head of an empty list is None.

    The lesson provides the ListNode class. A node has a val and a next pointer, and ListNode() with no argument makes a node whose val is 0 and whose next is None.

    With list1 = [1, 2, 4] and list2 = [1, 3, 4], the merged list is [1, 1, 2, 3, 4, 4]. With list1 = [-4, 10, 12] and list2 = [-7, 0] it is [-7, -4, 0, 10, 12]: once list2 is used up, the rest of list1 follows unchanged.

    Approach: always take the smaller front node

    Both lists are sorted, so the smallest value not yet placed is always at the front of one of them. Compare the two front nodes, move the smaller one to the end of the merged list, and repeat. Each node is looked at once, so the time is O(n + m) for lists of lengths n and m. Because nodes are re-linked rather than copied, the extra space is O(1).

    The awkward part is the very first node. The merged list starts empty, so attaching the first node would need a special case. The usual fix is a dummy node: a placeholder in front of the merged list. A variable tail starts on the dummy and always points to the last node of the merged list. Every node, including the first, is attached the same way, as tail.next. At the end, the real list is dummy.next.

    A recursive merge is shorter to write, but it makes one call per node. With up to 10,000 nodes in each list, the call stack runs out: on 20,000 nodes the recursive version raises RecursionError under Python's default limit. The loop has no such limit.

    Step by step

    1. Create the dummy node with ListNode() and store it in dummy. Its value is never used.
    2. Point tail at dummy. The merged list is just the dummy for now, so it is also its last node.
    3. Loop while both lists have nodes. None is falsy, so while list1 and list2: stops as soon as either list runs out.
    4. Compare the front values with list1.val <= list2.val. Using <= sends ties to list1, so equal values keep list1's before list2's.
    5. Attach list1's front node: tail.next = list1. This links the node itself.
    6. Advance list1 to list1.next. The attached node now belongs to the merged list.
    7. Otherwise attach list2's front node in an else branch, mirroring the first branch.
    8. Advance list2 to list2.next.
    9. Move tail forward to tail.next, after the if/else. Both branches attached a node, so this line is shared.
    10. Attach the leftover nodes in one step. When the loop ends, at least one list is empty. The other is already sorted, and none of its values is smaller than what was merged, so it is linked on as it is.
    11. Return dummy.next, the first real node. If both inputs were empty it is None.

    The solution in Python

    class Solution:
        def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
            dummy = ListNode()
            tail = dummy
            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
    

    Python details worth a look:

    • Truthiness of nodes. A node is an ordinary object, so it counts as true, and None counts as false. That is why while list1 and list2 works without comparing to None. A node whose val is 0 is still true, because the test applies to the node and not to its value.
    • Variables are names for nodes. list1 = list1.next only changes which node the name list1 refers to. The node that was attached keeps its own next until the following iteration overwrites it through tail.next, so the lists are not damaged.
    • The conditional expression. list1 if list1 else list2 gives list1 when it still has nodes and list2 otherwise. When both are used up it gives None, which correctly ends the list.
    • The lists are modified. The result reuses the input nodes: with list1 = [1] and list2 = [1], the returned head is the list1 node itself and its next is the list2 node.

    Complexity

    Time: O(n + m). Every iteration of the loop attaches one node and moves one pointer forward, so the loop runs at most n + m times. Attaching the leftover list is a single assignment.

    Space: O(1). The function keeps a dummy node and the variables tail, list1 and list2, whatever the list sizes.

    Edge cases and common mistakes

    • An empty list. With list1 = [] and list2 = [0] the loop never runs, the leftover step attaches list2, and the result is [0]. With both empty the result is [].
    • Returning dummy. The dummy is a placeholder with value 0. Returning it would put an extra 0 at the front of the answer.
    • Forgetting to advance tail. Each new node would overwrite the previous tail.next, and the merged list would end up with a single node.
    • Forgetting the leftover. After the loop one list can still have nodes, such as 10 -> 12 in the second example. Without the final attachment they would be lost.
    • Using < instead of <=. The result is still sorted, but ties then come from list2 first, so equal values no longer keep the order list1 before list2.
    • Recursion on long lists. Python's default recursion limit is about 1,000 calls, far below the 20,000 nodes the constraints allow.

    Testing

    • [1, 2, 4] and [1, 3, 4] give [1, 1, 2, 3, 4, 4].
    • [] and [0] give [0].
    • [-4, 10, 12] and [-7, 0] give [-7, -4, 0, 10, 12].
    • [] and [] give [].
    • [5] and [] give [5].
    • [1, 1] and [1] give [1, 1, 1].
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free