Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in Rust: O(n + m) with a Dummy Node

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 13
    Ctrl + Enter to check

    RUST · LINKED LISTS

    Merge Two Sorted Lists in Rust, explained

    Problem overview

    The function merge_two_lists receives the heads of two linked lists, list1 and list2, each sorted in ascending order. Each head is an Option<Box<ListNode>>, and None stands for an empty list. The function must return the head of one sorted list that contains all the nodes of both inputs.

    The result has to be made by splicing: the existing nodes are linked to each other, and no new node holds a copied value. The lesson provides the ListNode struct, with a val: i32, a next: Option<Box<ListNode>> and a ListNode::new(val) constructor.

    With list1 = [1, 2, 4] and list2 = [1, 3, 4] the result is [1, 1, 2, 3, 4, 4]. With list1 = [] and list2 = [0] it is [0], and with list1 = [-4, 10, 12] and list2 = [-7, 0] it is [-7, -4, 0, 10, 12]. Merging [] with [] gives [].

    Approach: always take the smaller front node

    Both lists are sorted, so the smallest value not yet used is always one of the two front nodes. Compare them, move the smaller one to the end of the merged list, and repeat. When one list runs out, the other one is already sorted and every node in it is at least as large as everything merged so far, so it can be attached whole.

    The statement asks for O(n + m) time, where n and m are the list lengths: every node is moved exactly once, with one comparison at most. The extra space is O(1) because no node is created or copied, only re-linked.

    A recursive merge is also possible, but it goes one call deeper for every node. With up to 10,000 nodes in each list, that can exhaust the call stack, so the lesson uses a loop.

    The dummy node

    Attaching the first node of the merged list is a special case: there is no previous node to attach it to. A dummy node removes that case. The merged list starts as a placeholder node with value 0, and a variable tail always points at the last node of the merged list, which is the dummy at first. Every node is then attached the same way, to tail.next, and the answer is dummy.next. The dummy's own value is never part of the result.

    Step by step

    1. Create the dummy. Box::new(ListNode::new(0)) goes into a mutable variable dummy. The parameters are declared mut in the signature, so the function can move list1 and list2 forward.
    2. Point tail at it with let mut tail = &mut dummy;. It is a mutable reference, so writing to tail.next changes the real node, and the variable itself is mut so it can later point to a different node.
    3. Loop while both lists have nodes. Once one is empty, there is nothing left to compare.
    4. Compare the front values. as_ref() borrows the Option without moving it, unwrap() reaches the box, and .val reads the number. Using <= sends the node from list1 first on a tie, which keeps equal values in a stable order.
    5. Cut the front node off its list. list1.as_mut().unwrap().next.take() moves the rest of the list out into rest and leaves None behind. Now the front node stands alone.
    6. Attach it by moving list1 into tail.next. This moves the existing box, which is why no new memory is needed.
    7. Advance the list: list1 = rest;. Assigning to list1 after it was moved out is allowed, because it gets a fresh value.
    8. The else branch does the same three things for list2.
    9. Move tail forward once, after the if/else, because both branches attach a node at tail.next: tail = tail.next.as_mut().unwrap();.
    10. Attach the leftovers. After the loop, at least one list is empty. tail.next becomes list1 if it is Some, and list2 otherwise. If both are empty, list2 is None, which ends the list correctly.
    11. Return dummy.next, with no semicolon. If both inputs were empty, that is still None.

    The solution in Rust

    struct ListNode {
        val: i32,
        next: Option<Box<ListNode>>,
    }
    
    impl ListNode {
        fn new(val: i32) -> Self {
            ListNode { val, next: None }
        }
    }
    
    impl Solution {
        fn merge_two_lists(mut list1: Option<Box<ListNode>>, mut list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
            let mut dummy = Box::new(ListNode::new(0));
            let mut tail = &mut dummy;
            while list1.is_some() && list2.is_some() {
                if list1.as_ref().unwrap().val <= list2.as_ref().unwrap().val {
                    let rest = list1.as_mut().unwrap().next.take();
                    tail.next = list1;
                    list1 = rest;
                } else {
                    let rest = list2.as_mut().unwrap().next.take();
                    tail.next = list2;
                    list2 = rest;
                }
                tail = tail.next.as_mut().unwrap();
            }
            tail.next = if list1.is_some() { list1 } else { list2 };
            dummy.next
        }
    }
    

    The Rust details worth a closer look:

    • Ownership does the splicing. Each node is owned by the Box in the previous node's next. tail.next = list1; moves ownership of the whole remaining chain of list1 into the merged list. That is only safe because take() already cut the rest off, so the moved chain is a single node.
    • take() on an Option replaces the value with None and returns the old value. It is the standard way to move something out of a field you only borrow.
    • as_ref() and as_mut() turn an &Option<Box<T>> into an Option<&Box<T>>, so unwrap() gives a reference and doesn't consume the list. Without them, list1.unwrap() would move the list out of the variable.
    • The reference and the dummy. While tail borrows dummy, nothing else may use dummy. The last use of tail is the assignment after the loop, so the borrow is over by the time dummy.next moves the answer out.
    • if is an expression. if list1.is_some() { list1 } else { list2 } produces one of the two lists as a value, so it can be assigned straight to tail.next.
    • The tail is the last expression. dummy.next has no semicolon, so it is the function's return value.

    Complexity

    Time: O(n + m). Each loop turn moves one node into the merged list, and the loop ends when one list is empty, after at most n + m - 1 turns. The leftover attach is a single assignment, not a walk.

    Space: O(1). The function holds the dummy node and a few references. The nodes of the result are the input nodes.

    Edge cases and common mistakes

    • An empty list. With [] and [0] the loop never runs, list1 is None, and tail.next becomes list2, so the result is [0].
    • Both empty. The result is None, because dummy.next was never set.
    • Unequal lengths. [-4, 10, 12] and [-7, 0] use up list2 after three nodes, and the rest of list1, 10 and 12, follows without more comparisons.
    • Forgetting take(). Moving list1 into tail.next without cutting next first would drag the whole remaining list along, and rest would have nothing to continue with.
    • Using unwrap() without as_ref(). It moves the list out of its variable, and the next use of the variable fails to compile.
    • Returning dummy. The placeholder value 0 would be the first node of the answer. The answer starts at dummy.next.
    • Using < instead of <=. The values still come out sorted, but on a tie the node from list2 would go first.

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