Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in Scala: 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 null). 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

    SCALA · LINKED LISTS

    Merge Two Sorted Lists in Scala, explained

    Problem overview

    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 merge splices the existing nodes together: it changes their next links and creates no copies. An empty list is represented by null, and either input, or both, can be empty.

    The lesson provides the node class. Each node has a field val holding an Int, which is why the code writes it in backticks, and a field next pointing to the following node or null. Its val parameter has a default of 0, so ListNode() builds a node holding 0.

    For list1 = [1,2,4] and list2 = [1,3,4] the result is [1,1,2,3,4,4]. For [] and [0] it is [0], and for [-4,10,12] and [-7,0] it is [-7,-4,0,10,12]. The statement asks for 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 at the front of one of them. So the merge repeats one move: compare the two front nodes, attach the smaller one to the end of the merged list, and advance in the list it came from. Each node is attached once, so the loop does at most n + m steps.

    When one list runs out, the other still holds a sorted run of nodes that are all at least as large as everything merged so far. Nothing remains to compare, so that whole run can be hooked on in one assignment.

    The only awkward part is the very first node. The merged list is empty at that point, so there is no last node to attach to. The lesson avoids a special case with a dummy node: a throwaway node placed in front of the merged list. A tail variable starts on the dummy and always stands on the merged list's last node. Every node, the first one included, is attached with tail.next = ..., and the answer is dummy.next.

    A recursive merge is shorter to write, but it makes one call per node, so two lists of 10,000 nodes mean 20,000 nested calls. The loop uses no call stack, and that is what the lesson builds.

    Step by step

    1. Copy the parameters into variables. Scala parameters can't be reassigned, and the code has to walk along both lists. node1 and node2 are vars that start at the two heads and always stand on the front node of what is left of each list.
    2. Create the dummy. ListNode() goes in a val, since the dummy itself never changes. The merged list hangs off dummy.next.
    3. Declare tail. It is a var because it moves, and it starts on the dummy, which at that moment is the whole merged list.
    4. Loop while both lists have nodes. Once either front is null, there is nothing to choose between.
    5. Compare the front values with <=. On a tie the node from list1 goes first, so equal values keep their original order.
    6. Attach and advance. In the if branch, tail.next becomes node1 and node1 moves to its own next. The else branch does the same for node2.
    7. Move tail forward once, after the if/else, because both branches attached a node at tail.next.
    8. Attach the leftovers. After the loop, tail.next becomes node1 if that is not null, and node2 otherwise. If both are used up, node2 is null, which correctly ends the list.
    9. Return dummy.next as the last expression. It is the first real node, or null when both inputs were empty.

    The solution in Scala

    class Solution {
        def mergeTwoLists(list1: ListNode, list2: ListNode): ListNode = {
            var node1 = list1
            var node2 = list2
            val dummy = ListNode()
            var tail = dummy
            while (node1 != null && node2 != null) {
                if (node1.`val` <= node2.`val`) {
                    tail.next = node1
                    node1 = node1.next
                } else {
                    tail.next = node2
                    node2 = node2.next
                }
                tail = tail.next
            }
            tail.next = if (node1 != null) node1 else node2
            dummy.next
        }
    }
    

    The Scala details worth a closer look:

    • Backticks around val. val is a keyword, so a field with that name can only be written as node1.`val`. Without the backticks the code does not compile.
    • if is an expression. if (node1 != null) node1 else node2 produces a value, so it can sit on the right-hand side of an assignment. Both branches are ListNodes, so the types agree.
    • No new. Scala 3 lets you create an instance with ListNode(), as if the class were a function. new ListNode() means the same.
    • null comparisons. node1 != null compares values and works with null too. A var holding a node reference is rebindable, but assigning to node1 never changes the caller's list1.
    • The last expression is the result. dummy.next has no return in front of it, and its type, ListNode, matches the declared return type.

    Complexity

    Time: O(n + m). Each iteration of the loop attaches one node and advances one of the two pointers, and no pointer ever moves back, so the loop runs at most n + m times. The leftover attachment is a single assignment.

    Space: O(1). The code allocates one dummy node and four variables, however long the lists are. The nodes in the result are the input nodes, relinked.

    Edge cases and common mistakes

    • An empty list. With list1 = null the loop never runs and tail.next becomes list2, so the result is list2 as it is. With both lists empty the function returns null.
    • Returning dummy. The dummy holds a placeholder 0 and is not part of the answer. The result starts at dummy.next.
    • Forgetting to advance tail. Each new attachment would overwrite the previous one, and the result would lose nodes.
    • Forgetting the leftovers. For [-4,10,12] and [-7,0] the loop ends after 0 is attached, and 10 and 12 would be dropped without the final line.
    • Using < instead of <=. The merged values would still be sorted, but equal values from list2 would go first. Using <= keeps list1's nodes ahead on a tie.
    • Merging two lists with equal values. Merging [1,1,1] and [1,2] gives [1,1,1,1,2].

    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 [], and the returned head is null.
    • Merging two lists of 10,000 nodes each, one with the even numbers and one with the odd numbers, gives a sorted list of 20,000 nodes.
    • For two single-node lists holding 5, the returned head is the node from list1, and its next is the node from list2.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free