Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in Swift: Splicing Nodes with a Dummy Head

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

    SWIFT · LINKED LISTS

    Merge Two Sorted Lists in Swift, explained

    Problem overview

    The method mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) receives the heads of two linked lists, each sorted in ascending order, and returns the head of one sorted list that holds all their nodes. An empty list is represented by nil, and either list, or both, may be empty. The lesson provides the ListNode class: each node has a val and an optional next, and ListNode() with no arguments makes a node with value 0 and no next node.

    For list1 = [1, 2, 4] and list2 = [1, 3, 4], the method returns the list [1, 1, 2, 3, 4, 4]. For list1 = [] and list2 = [0] it returns [0]. For list1 = [-4, 10, 12] and list2 = [-7, 0] it returns [-7, -4, 0, 10, 12].

    The statement asks you to splice the existing nodes together rather than create new ones, in O(n + m) time and O(1) extra space.

    Approach: always take the smaller front node

    Both lists are sorted, so the smallest value not yet used is always at the front of one of them. That gives a simple rule: compare the two front nodes, move the smaller one to the end of the merged list, and repeat. Each comparison places one node for good, so the loop runs at most n + m times.

    When one list runs out, the other still holds nodes that are sorted and no smaller than anything merged so far. They can be attached in one move, without more comparisons.

    The awkward part is the first node. The merged list is empty at the start, so there is no last node to attach to, and the code would need a special case for the first attachment. A dummy node removes it. The merged list starts as a single throwaway node, every real node is attached after the current last node in the same way, and the answer is whatever follows the dummy.

    A recursive version, which merges the rest of the lists after choosing the front node, also works, but it goes one call deeper per node. With up to 20,000 nodes that can exhaust the call stack, so a loop is the safer choice.

    On a tie, <= takes the node from list1 first, so equal values keep their original order. With a pair of nodes that both hold 1, the merged list starts with the node from list1, followed by the one from list2.

    Step by step

    1. Make mutable copies of the parameters. Swift parameters are constants, and the loop has to move both heads forward. var list1 = list1 declares a new variable with the same name that hides the parameter, so the rest of the code works on the copy.
    2. Create the dummy node with ListNode() and store it in a let. The variable always refers to the same node, so let is enough: only the node's next changes.
    3. Declare tail with var, starting at dummy. It always stands on the last node of the merged list, the one the next node gets attached to. At the start the merged list is just the dummy.
    4. Loop while both lists have nodes. Once one is empty, there is nothing left to compare.
    5. Compare the fronts with list1!.val <= list2!.val. The ! unwraps each optional, and the loop condition guarantees that neither is nil.
    6. Attach the smaller node. If it is list1's, set tail.next = list1. This links the existing node itself, so no new node is created.
    7. Advance that list with list1 = list1!.next. The attached node now belongs to the merged list, so what remains of list1 starts after it.
    8. Mirror both steps in the else branch for list2.
    9. Move tail forward with tail = tail.next!. Both branches just set tail.next to a node, so it is not nil, and one shared line after the if/else does the move.
    10. Attach the leftovers after the loop. At least one list is used up, so tail.next = list1 != nil ? list1 : list2 picks the one that still has nodes. If both are empty, list2 is nil, which ends the merged list correctly.
    11. Return dummy.next, the first real node. The dummy itself is not part of the answer.

    The solution in Swift

    class Solution {
        func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
            var list1 = list1
            var list2 = list2
            let dummy = ListNode()
            var tail = dummy
            while 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!
            }
            tail.next = list1 != nil ? list1 : list2
            return dummy.next
        }
    }
    

    The Swift details worth a closer look:

    • Shadowing a parameter. Writing list1 = list1!.next directly on the parameter fails to compile: cannot assign to value: 'list1' is a 'let' constant. The line var list1 = list1 is allowed because it creates a new variable in the function's scope.
    • Optionals need unwrapping. list1.val on a ListNode? is a compile error: value of optional type 'ListNode?' must be unwrapped to refer to member 'val' of wrapped base type 'ListNode'. The code uses ! because the loop condition has just proved the value is not nil. Without that guarantee, ! on a nil crashes the program.
    • Classes are reference types. ListNode is a class, so tail = dummy makes tail refer to the same object, not a copy. That is why tail.next = list1 changes the dummy's chain, and why a let constant for dummy can still have its next changed.
    • The nodes are reused. After merging [1, 3] with [2], the returned head is the very node that was the head of the first list, and its next is the node of the second list. Nothing is copied.
    • The conditional operator. condition ? a : b gives a when the condition is true and b otherwise. Both sides have the type ListNode?, so the result can be assigned to tail.next.

    Complexity

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

    Space: O(1). The method creates one dummy node and a few variables. The merged list is made of the nodes that were already there.

    Edge cases and common mistakes

    • Empty lists. With list1 = [] and list2 = [0] the loop never runs, and the leftover step attaches list2, giving [0]. With both empty, dummy.next stays nil, which is the empty list.
    • One list much shorter. For [-4, 10, 12] and [-7, 0], the loop places -7, -4 and 0, then list2 is empty and 10 -> 12 is attached as it is.
    • Forgetting the leftovers. Without the line after the loop, everything left in the longer list is dropped.
    • Returning dummy. That includes the placeholder node with value 0 at the front of the answer. Return dummy.next.
    • Forgetting to advance tail. Each attachment would overwrite the previous one, and the earlier nodes would be lost from the merged list.
    • Using < instead of <=. The merged values are the same, but on ties the nodes from list2 would come first, so equal values would no longer keep their original order.

    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].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free