Merge Two Sorted Lists

EasyLinked List · Recursion🧩 Recursion & Divide and ConquerLeetCode #21 ↗Updated

Problem

You are given the heads of two singly linked lists, each already sorted in non-decreasing order. Combine them into one sorted list by re-linking the existing nodes, and return the head of the merged list.
Input[1,2,4], [1,3,4]Output[1,1,2,3,4,4]
Input[], []Output[]
Input[], [0]Output[0]

0 ≤ nodes per list ≤ 50  ·  -100 ≤ Node.val ≤ 100  ·  both lists sorted non-decreasing

Try it yourself

Java
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The smallest remaining node is always one of the two heads. Repeatedly take the smaller head and append it; when one list runs out, the other's remainder is already sorted and can be attached in one step.
PatternRecursion & Divide and Conquer

Instinct If the answer for n items can be built from the same problem on halves (or smaller pieces) plus a cheap combine step - split, recurse, merge.

Memory hack Split it, trust it, stitch it - nail the base case, take the leap of faith on smaller calls, then glue their answers together.

Open the Recursion & Divide and Conquer guide →

Approaches

Brute ForceCollect, Sort, Rebuild

Time O((n+m) log(n+m))Space O(n+m)

Ignore the sortedness: dump every value from both lists into one array, sort it, and build a fresh list from the sorted values.

Java
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    List<Integer> vals = new ArrayList<>();
    for (ListNode c = list1; c != null; c = c.next) vals.add(c.val);
    for (ListNode c = list2; c != null; c = c.next) vals.add(c.val);
    Collections.sort(vals);
    ListNode dummy = new ListNode(0), tail = dummy;
    for (int v : vals) {
        tail.next = new ListNode(v);
        tail = tail.next;
    }
    return dummy.next;
}

Works for any input, but wastes the given order and allocates new nodes.

At a glance

LevelApproachTimeSpace
Brute ForceCollect, Sort, RebuildO((n+m) log(n+m))O(n+m)
BetterRecursive MergeO(n+m)O(n+m) stack
OptimalIterative Merge with Dummy HeadO(n+m)O(1)
Common pitfalls
  • Returning dummy instead of dummy.next.
  • Looping until both lists are null node-by-node instead of attaching the leftover once.
  • Forgetting to advance tail — every node overwrites the same link.
Interview tips
  • Introduce the dummy head early; it simplifies many list problems.
  • Offer the recursive version too, and note its O(n+m) call stack.
  • Test aloud with one or both lists empty.
Pattern
Two-pointer merge (dummy head) → combine sorted sequences, the core step of merge sort and k-way merge.
My notes saved in this browser