Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in Kotlin: 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

    KOTLIN · LINKED LISTS

    Merge Two Sorted Lists in Kotlin, explained

    Problem overview

    mergeTwoLists receives list1 and list2, the heads of two singly linked lists that are each sorted in ascending order. It returns the head of one sorted list that holds all the nodes of both. An empty list is represented by null, so either argument, or both, can be null.

    The lesson provides the node class: ListNode has an Int field named val and a nullable next. Because val is a Kotlin keyword, the field is written with backticks, node.`val`.

    For list1 = [1,2,4] and list2 = [1,3,4] the result is [1, 1, 2, 3, 4, 4]. With [] and [0] it is [0], and with [-4,10,12] and [-7,0] it is [-7, -4, 0, 10, 12]. The statement asks for the nodes to be spliced together, not copied: the answer is built by re-linking the nodes that already exist, so the extra space is O(1).

    Approach

    Both lists are sorted, so the smallest value not yet used is always at the front of one of them. Compare the two front nodes, attach the smaller one to the end of the merged list, and move that list's head forward. Repeat until one list runs out. The rest of the other list is already sorted and every value in it is at least as large as what was merged, so it can be attached in one step.

    The awkward part is the first node. The merged list is empty at the start, so there is no node whose next could point at the first choice. A dummy node removes that special case: it sits in front of the merged list, every real node is attached after the current last node in the same way, and the answer is dummy.next.

    A recursive merge is shorter to write, but it makes one call per node, and the lists can hold 10,000 nodes each. A loop uses no call stack, and that is what this lesson does. The loop runs once per attached node, so the time is O(n + m) for lists of length n and m.

    Step by step

    1. Make mutable copies of the parameters. Kotlin parameters are read-only, but the loop has to move both heads forward. var list1 = list1 creates a variable with the same name that hides the parameter.
    2. Create the dummy node with ListNode() and keep it in a val. It never changes, so it can't be lost, and at the end it still points at the front of the merged list.
    3. Create tail, a var that starts on dummy. It always stands on the last node of the merged list.
    4. Loop while both lists have nodes. Inside the loop Kotlin knows that list1 and list2 are not null (a smart cast, possible because they are local variables), so their fields can be read directly.
    5. Compare the front values with <=. On a tie the node from list1 goes first, so equal values keep their order.
    6. Attach and advance. In the first branch set tail.next to list1, then move list1 to its next. The else branch does the same with the lists swapped.
    7. Move tail onto the node just attached. Both branches end the same way, so this line comes after the if/else. Since next has the type ListNode?, !! tells the compiler it is not null here.
    8. Attach the leftovers. When the loop ends, at least one list is empty. if (list1 != null) list1 else list2 is an expression, so it can be assigned straight to tail.next. If both lists are used up, it assigns null, which correctly ends the list.
    9. Return dummy.next, the first real node. If both inputs were empty, that is null, an empty list.

    The solution in Kotlin

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

    Some Kotlin details in this code:

    • var list1 = list1 compiles because the new local variable shadows the parameter. After that line, every use of list1 in the function refers to the variable.
    • `val` in backticks lets a keyword be used as a name. Without them list1.val doesn't compile.
    • tail.next!! throws an exception if next is null. It can't be here, because the line above, in one of the two branches, just assigned a non-null node.
    • Splicing reuses the original ListNode objects. After merging [1,2,4] and [1,3,4], the returned head is the first node of list1 itself (=== compares references and gives true), and its next is the first node of list2. That also means the input lists are changed: after the call, the old heads are parts of the merged list.

    Complexity

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

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

    Edge cases and common mistakes

    • Empty lists. With [] and [0] the loop never runs and tail.next becomes list2, so the result is [0]. With two empty lists the result is null.
    • One list much shorter. With [-4,10,12] and [-7,0], the values -7, -4 and 0 are attached one by one, then 10 -> 12 follows without any more comparisons.
    • Ties. Using < instead of <= still gives a sorted list, but equal values from list2 would come first. Using <= keeps list1's node first, as in the example.
    • Forgetting to advance tail. Without tail = tail.next!! each new node overwrites the previous one's place, and the merged list keeps only the last node attached.
    • Returning dummy. The dummy is not part of the answer, so return dummy.next.

    Testing

    Run the function on these inputs and compare:

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