Start learning free

LESSON 156 OF 314 · LINKED LISTS

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

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

    TYPESCRIPT · LINKED LISTS

    Merge Two Sorted Lists in TypeScript, explained

    Problem overview

    The method 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. The lesson provides the ListNode class: each node has a val and a next that points to the following node, or is null at the end of a list. An empty list is represented by null.

    The merged list must be made of the existing nodes, linked to each other, not of copies. For list1 = [1,2,4] and list2 = [1,3,4] the result is [1,1,2,3,4,4]. When two front nodes hold equal values, the one from list1 goes first.

    Approach

    Both lists are sorted, so the smallest value that has not been placed yet is always one of the two front nodes. Compare them, take the smaller one, and repeat. This is the merge step of merge sort, done on linked nodes.

    Taking a node means re-linking it: the merged list's last node gets its next set to the chosen node, and the chosen list moves one node forward. No node is created or copied, so the extra space is O(1), and each node is handled once, so the time is O(n + m) for lists of length n and m.

    There are two decisions worth understanding:

    • A dummy node. The head of the merged list is not known until the first comparison. Starting from a placeholder node in front of it means that attaching the first real node is the same operation as attaching every later one. The answer is the node after the placeholder.
    • A loop, not recursion. A recursive merge adds one call to the stack per node. With up to 10,000 nodes in each list that is 20,000 nested calls, which can exceed the call stack. The loop uses constant space.

    Step by step

    1. Create the placeholder. dummy is a new ListNode. It is declared with const because the variable always names the same node; its fields still change. Its own value is never used.
    2. Track the end of the merged list. tail starts at dummy and is declared with let, because it moves forward. It always points at the node that the next one will be attached to.
    3. Loop while both lists have nodes. Only then is there a comparison to make. The test uses !== null on both lists.
    4. Pick the smaller front node. If list1.val <= list2.val, attach list1 to tail.next and move list1 to list1.next. Otherwise do the same with list2. The <= is what puts the node from list1 first on a tie, so equal values keep their original order.
    5. Advance tail. Both branches attach a node at tail.next, so one line after the if/else moves tail onto it.
    6. Attach the leftovers. When the loop ends, at least one list is empty. The other still holds sorted nodes that are all at least as large as everything merged so far, so the whole remainder is linked in one assignment, without more comparisons. If list1 is not null it is the remainder; otherwise list2 is, and if both are empty that is null, which ends the list correctly.
    7. Return dummy.next. The placeholder is not part of the answer.

    The solution in TypeScript

    class Solution {
        mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
            const dummy = new ListNode();
            let 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 = list1 !== null ? list1 : list2;
            return dummy.next;
        }
    }
    

    Some details for TypeScript:

    • Parameters can be reassigned. list1 and list2 are ordinary local variables, so the loop moves them along their lists. The caller's variables are not affected, but the nodes themselves are shared: the returned list is built from the very nodes that were passed in.
    • The types are checked only by the compiler. ListNode | null documents that a list may be empty, but nothing is checked when the program runs; the loop's !== null tests are what actually protect list1.val and list2.val.
    • The conditional operator condition ? a : b gives a when the condition is true and b otherwise, which makes the leftover step a single line.
    • Nodes are reused. Merging the lists 1 → 3 and 2 returns the original first node of the first list, and its next is the original node of the second list.

    Complexity

    Time: O(n + m). Each loop turn moves one node from an input list into the merged list, and the leftover is attached in one step. Space: O(1). The code keeps only dummy, tail and the two moving pointers, and creates one node in total.

    Edge cases and common mistakes

    • Both lists empty. The loop does not run, tail.next is set to list2, which is null, and dummy.next is null: an empty list.
    • One list empty. With list1 = [] and list2 = [0] the loop is skipped and the leftover step returns the second list as it is.
    • One list much shorter. For [-4,10,12] and [-7,0] the second list runs out after the three comparisons that place -7, -4, 0, and 10 → 12 is attached whole.
    • Forgetting the leftover step. The loop stops as soon as one list is empty, so without the final attach the rest of the other list is lost.
    • Returning dummy instead of dummy.next. The result would start with an extra node of value 0.
    • Forgetting to move tail. Each new node would overwrite the previous one's place and the merged list would keep only the last node.

    Testing

    These inputs, run through the method, give:

    list1list2Result
    [1,2,4][1,3,4][1,1,2,3,4,4]
    [][0][0]
    [-4,10,12][-7,0][-7,-4,0,10,12]
    [][][]
    [5][][5]
    [1,1][1,1][1,1,1,1]

    Two lists of 10,000 nodes each (the even and the odd numbers) merge into one sorted list of 20,000 nodes without any trouble.

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free