Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in Go: Dummy Node, O(n + m) Time

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 nil). 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 12
    Ctrl + Enter to check

    GO · LINKED LISTS

    Merge Two Sorted Lists in Go, explained

    Problem overview

    The function mergeTwoLists receives list1 and list2, pointers to the first nodes of two linked lists. Each list is sorted in ascending order. It must return the head of a single sorted list that contains every node of both inputs. The nodes have to be spliced together: the existing nodes are re-linked, and no new ones are created. Either list can be empty, and an empty list is a nil pointer. The lesson provides the ListNode type, which has an integer Val and a Next pointer to the following node.

    For list1 = [1, 2, 4] and list2 = [1, 3, 4] the merged list is [1, 1, 2, 3, 4, 4]. For 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 as it is.

    The target is O(n + m) time and O(1) extra space, where n and m are the two lengths.

    Approach: always take the smaller front node

    Because both lists are sorted, the smallest value not yet placed is always one of the two front nodes. Compare them, attach the smaller one to the end of the merged list, and advance in the list it came from. Every node is looked at once, so the time is linear in the total number of nodes. Nothing is allocated per node, because attaching is just assigning a pointer.

    The awkward part is the first node: the merged list is empty at the start, so there is no node whose Next can be set. A dummy node removes that case. The merged list starts as one placeholder node, tail points at its last node, and every real node is attached after tail in the same way. At the end, the answer is the node after the placeholder.

    A recursive merge is also possible, but it goes one call deeper for every node, so long lists need a lot of call stack. The loop uses a fixed amount of memory however long the lists are.

    Step by step

    1. Create the placeholder. &ListNode{} makes a zero-valued node and gives its address, which goes into dummy. The merged list will hang off dummy.Next.
    2. Create tail. It starts on dummy, which at this point is the whole merged list.
    3. Loop while both lists have nodes. Go has no while, so this is a for with only a condition. When one list runs out, there is nothing left to compare.
    4. Compare the front values with list1.Val <= list2.Val. Using <= means that on a tie the node from list1 goes first, so equal values keep their original order.
    5. Attach and advance. In the first branch, set tail.Next = list1, then move list1 to its next node. The node now belongs to the merged list, so what remains of list1 starts after it.
    6. Mirror it for list2 in the else branch.
    7. Move tail forward once, after the if/else. Both branches attach a node at tail.Next, so one shared line moves tail onto it.
    8. Attach the leftovers. After the loop, at least one list is empty. The other one is still sorted, and none of its nodes is smaller than what is already merged, so it can be attached whole. Go has no conditional operator, so an if/else chooses between list1 and list2.
    9. Return dummy.Next. The dummy node itself is not part of the answer.

    The solution in Go

    func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
        dummy := &ListNode{}
        tail := dummy
        for list1 != nil && list2 != nil {
            if list1.Val <= list2.Val {
                tail.Next = list1
                list1 = list1.Next
            } else {
                tail.Next = list2
                list2 = list2.Next
            }
            tail = tail.Next
        }
        if list1 != nil {
            tail.Next = list1
        } else {
            tail.Next = list2
        }
        return dummy.Next
    }
    

    Go details worth knowing:

    • Pointers and nil. *ListNode is a pointer, and an empty list is the nil pointer. Go lets you write list1.Val on a pointer without any dereferencing syntax, but doing it on nil panics. The loop condition and the final if make sure that never happens.
    • &ListNode{} and :=. The composite literal builds a node with Val 0 and Next nil, and & takes its address. := declares the variable and infers the type *ListNode.
    • Parameters are copies of the pointers. Moving list1 and list2 forward changes only the function's local copies, not the caller's variables. The nodes themselves are shared, so the returned list is made of the caller's original nodes.
    • The final else needs no nil test. If both lists are empty, list2 is nil, and assigning it to tail.Next correctly ends the list.

    Complexity

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

    Space: O(1). The function uses one dummy node and a few pointers, whatever the sizes of the lists. The merged list reuses the input nodes.

    Edge cases and common mistakes

    • Empty lists. With [] and [0] the loop never runs, the leftover step attaches [0] and the result is [0]. With two empty lists the result is nil, which is the empty list.
    • Ties. With [2, 2] and [2] the result is [2, 2, 2]. With <=, the first node of the result is always list1's node when the fronts are equal.
    • Returning dummy instead of dummy.Next. The result would start with an extra node of value 0.
    • Forgetting to move tail. Each attachment would overwrite the previous one, and the merged list would keep only the last node.
    • Forgetting the leftover. If the loop ends and the remaining nodes are not attached, they are lost: [-4, 10, 12] and [-7, 0] would end at 0.
    • Walking the leftover node by node. It works, but it is unnecessary, because the remaining nodes are already linked in order.

    Testing

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