Merge two sorted linked lists

medium

Given the head pointers of two sorted linked lists, both arranged in non-decreasing order, merge them into one sorted list and return the head of the result.

You must splice the nodes together — no value is dropped, no value is added. Every node from both inputs appears exactly once in the output, and the output stays sorted from smallest to largest.

Think of it like merging two already-sorted stacks of numbered cards into a single sorted pile: at each step you take the smaller card from the top of one stack. Because each stack is already ordered, you never have to look deeper than the top card.

Hints

You have two piles that are each already sorted. What's the very first value of the merged result guaranteed to be?
You never have to look past the front of each list — the smallest remaining value is always one of the two current heads.
Build the answer behind a dummy node, and at each step link the smaller of the two heads, then advance that pointer.

Common doubts

It gives you a fixed node to append behind, so the first append is no different from the rest. You return dummy.next as the real head.
Take either one — the result stays sorted. Using <= picks the node from head1 first, which keeps the merge stable.
No. The optimal solution re-links the existing nodes, so it uses only O(1) extra space. The brute force allocates copies, which is wasteful here.

Interview follow-ups

Use a min-heap of the k current heads (pop the smallest, push its next), giving O(N log k), or merge them pairwise like the merge step of merge sort.
Yes — pick the smaller head as the start, then splice, but you'll need an explicit check for which list begins the result. The dummy node exists precisely to avoid that special case.

Fun facts

  • This exact two-pointer weave is the merge in merge sort — the step that makes the whole algorithm O(n log n).
  • The same idea scales to external sorting: databases merge sorted runs from disk that are far too big to fit in memory.

Asked at

AmazonMicrosoftGoogleAdobeMeta
Frequently Sometimes Occasionally
Example 1
Input: head1 = [5,10,15,40], head2 = [2,3,20]
Output: [2,3,5,10,15,20,40]
Interleaving the two sorted lists keeps every value in non-decreasing order.
Example 2
Input: head1 = [1,2,4], head2 = [1]
Output: [1,1,2,4]
The single node `1` from head2 slots in front of head1's `2`, and the rest follow in order.
Constraints

- 1 <= number of nodes in list1 <= 10^3 - 1 <= number of nodes in list2 <= 10^3 - 0 <= node value <= 10^5 - Both input lists are sorted in non-decreasing order.

Solve this problem →