Start learning free

LESSON 437 OF 671 · LINKED LISTS

Merge Two Sorted Lists in JavaScript: 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 11
    Ctrl + Enter to check

    JAVASCRIPT · LINKED LISTS

    Merge Two Sorted Lists in JavaScript, explained

    Problem overview

    mergeTwoLists(list1, list2) receives the heads of two singly linked lists, each sorted in ascending order, and returns the head of one sorted list that contains all of their nodes. Either list can be empty, and an empty list is represented by null.

    The lesson provides the ListNode constructor: each node has a val (default 0) and a next (default null). The merged list has to be built by linking the existing nodes, not by creating copies.

    For list1 = [1, 2, 4] and list2 = [1, 3, 4] the result is [1, 1, 2, 3, 4, 4]. When two front values are equal, the node from list1 goes first, so equal values keep their original order.

    Approach: always take the smaller front node

    Because both lists are sorted, the smallest value not yet used is always one of the two front nodes. So the merge repeats one decision: compare the fronts, attach the smaller node to the end of the merged list, and move that list forward. This is the merge step of merge sort.

    The statement asks for O(n + m) time and O(1) extra space, where n and m are the lengths of the lists. Each node is attached once, so the time is linear. No node is created except one placeholder, so the extra space is constant.

    Two design choices matter:

    • A dummy node. The first node of the merged list would need special handling, because there is no previous node to attach it to. A placeholder node in front removes that case: every node is attached after the current last node in the same way, and the answer is the node after the placeholder.
    • A loop instead of recursion. A recursive merge goes one call deeper for every node. With up to 10,000 nodes in each list, that can run out of call stack. The loop uses no extra stack.

    Step by step

    1. Create the placeholder. new ListNode() gives a node with val 0 and next null. It is stored in a const, because the name dummy always refers to this same node.
    2. Create tail with let. It points at the last node of the merged list, which for now is the placeholder. It will move, so it can't be a const.
    3. Loop while both lists have nodes. Compare with !== null. Once one list is empty there is nothing left to compare.
    4. Compare the fronts with list1.val <= list2.val. Using <= rather than < sends ties to list1.
    5. Attach the smaller node by setting tail.next to it. This links the existing node itself.
    6. Advance that list to its next node, since the front node now belongs to the merged list.
    7. Handle the other case with an else branch that mirrors the first one for list2.
    8. Advance list2 inside the else.
    9. Move tail to the node just attached. Both branches attach at tail.next, so this one line comes after the if/else.
    10. Attach the leftovers in one step. After the loop at least one list is empty. The remaining nodes are already sorted and none is smaller than what has been merged, so one assignment links the whole rest.
    11. Return dummy.next, the first real node. The placeholder isn't part of the answer.

    The solution in JavaScript

    class Solution {
        mergeTwoLists(list1, list2) {
            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;
        }
    }
    

    The JavaScript details worth a look:

    • const protects the name, not the object. dummy can't be reassigned, but dummy.next can be changed freely. tail is reassigned on every pass, so it uses let.
    • Parameters are ordinary local variables. The loop reassigns list1 and list2. That changes only the function's own variables, not the caller's. The nodes themselves are shared, though: their next fields really are changed.
    • !== null. Empty lists are null, so comparing with !== is exact. A node object is always truthy, so while (list1 && list2) would also work.
    • The conditional operator. list1 !== null ? list1 : list2 gives list1 if it still has nodes and list2 otherwise. If both are used up, it gives list2, which is null, and that ends the merged list correctly.

    After a merge, the input lists are no longer separate. With list1 = [1, 3] and list2 = [1], the returned head is the original first node of list1, and its next is the original list2 node.

    Complexity

    Time: O(n + m). Each pass of the loop attaches one node and moves one pointer forward, so the loop runs at most n + m times. The final attachment is a single assignment.

    Space: O(1). The function creates one placeholder node and uses a few variables. The merged list reuses the input nodes.

    Edge cases and common mistakes

    • Empty lists. With list1 = null and list2 = [0] the loop never runs, tail.next becomes list2, and the result is [0]. With both empty, dummy.next is still null.
    • One list much longer. For [-4, 10, 12] and [-7, 0], list2 runs out after -7, -4 and 0 are placed. The rest, 10 -> 12, is attached without more comparisons.
    • Forgetting to move tail. Every new node would then replace the previous one at tail.next, and the merged list would lose nodes.
    • Forgetting the leftovers. Without the assignment after the loop, the rest of the longer list is dropped.
    • Returning dummy. That adds a stray 0 at the front of the answer.
    • Using < for ties. The result has the same values, but equal values from list2 would come before those of list1, which breaks the order the lesson expects.
    • Recursion. It's shorter to write, but its depth grows with the number of nodes, so the loop is the safer choice for long lists.

    Testing

    Outputs of the solution, with the lists written as arrays:

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