DSA and coding Level 1 This level · 12 of 19
Easy dsa linked-lists

Merge Two Sorted Lists

The 30 second answer

Both lists are already sorted, so I attach the smaller current head to a dummy node and advance that list. When one list runs out I attach the rest of the other. A dummy head saves a special case for the first node, and the merge is in place on the existing nodes.

Could you say this in an interview?

Problem Merge two sorted linked lists and return the head of the merged sorted list. The merge should reuse the existing nodes. Original: LeetCode 21: Merge Two Sorted Lists.

Understanding the prompt The inputs may be empty. Equal values can be taken from either list; taking from the first one keeps the merge stable. You should not allocate new nodes for the values, only rewire next pointers.

Pattern recognition Merge two sorted sequences, with a dummy head so you never need a special case for an empty result prefix.

Brute force Copy values into an array, sort, and rebuild a list: O((n + m) log (n + m)) and extra nodes.

Optimal A dummy node and a tail pointer t. While both lists are non-null, attach the smaller head to t and advance that list and t. Then attach whichever list still has nodes. Return dummy.next.

Alternatives A recursive version, mergeTwoLists(a, b) attaching the smaller head to the merge of the rest, is short but uses O(n + m) stack space. The iterative dummy-head version is the one to write first.

Java solution

public class MergeTwoSortedLists {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    static ListNode list(int... a) {
        var dummy = new ListNode(0);
        var t = dummy;
        for (int x : a) {
            t.next = new ListNode(x);
            t = t.next;
        }
        return dummy.next;
    }

    static String str(ListNode h) {
        var sb = new StringBuilder("[");
        for (ListNode p = h; p != null; p = p.next) {
            if (sb.length() > 1) sb.append(", ");
            sb.append(p.val);
        }
        return sb.append("]").toString();
    }

    static ListNode mergeTwoLists(ListNode a, ListNode b) {
        var dummy = new ListNode(0);
        var t = dummy;
        while (a != null && b != null) {
            if (a.val <= b.val) { t.next = a; a = a.next; }
            else { t.next = b; b = b.next; }
            t = t.next;
        }
        t.next = a != null ? a : b;
        return dummy.next;
    }

    public static void main(String[] args) {
        System.out.println(str(mergeTwoLists(list(1, 2, 4), list(1, 3, 4)))); // [1, 1, 2, 3, 4, 4]
        System.out.println(str(mergeTwoLists(null, null)));                   // []
        System.out.println(str(mergeTwoLists(null, list(0))));                // [0]
    }
}

Complexity O(n + m) time, O(1) extra space besides the reused nodes.

Edge cases

  • Official samples: 1 -> 2 -> 4 and 1 -> 3 -> 4 merge to 1 -> 1 -> 2 -> 3 -> 4 -> 4.
  • Both empty returns null.
  • One empty list, as in null and [0], returns the other list.

Follow-ups

  • Merge k sorted lists uses a heap, or repeated pairwise merges.
  • Sort List is merge sort on a list, and this routine is the combine step.

Tests [1,2,4] and [1,3,4] merge to [1,1,2,3,4,4]. Two empty lists return []. An empty list and [0] return [0].

How to say it in the interview "I use a dummy head and always attach the smaller of the two current nodes, then splice on whatever is left when one list runs out. That reuses the existing nodes and stays linear with constant extra space."

Sources (1)
  1. LeetCode 21: Merge Two Sorted Listsleetcode.com
Previous
Next