datarekha
Coding Patterns Easy Asked at AmazonAsked at GoogleAsked at Meta

Merge two sorted linked lists into one sorted list.

The short answer

Use a dummy head node to avoid special-casing the result's first element. Walk both lists with two pointers, always appending the smaller current node to the result. When one list is exhausted, append the remainder of the other. O(n + m) time, O(1) space.

How to think about it

Recognise the pattern

This is the merge step of merge sort, applied to linked lists. Two-pointer merge on sorted sequences is a building block you will see again in merge k sorted lists, external sorting, and database join algorithms. Recognise it whenever you need to interleave two ordered sequences optimally.

Build the approach step by step

Brute force: dump both lists into an array, sort, rebuild a linked list. O((n+m) log(n+m)) — wastes the existing sorted order entirely.

Two-pointer merge:

We want to pick the smaller head at each step. The complication with linked lists is handling the very first node without special-casing it. The standard trick: dummy sentinel node.

  1. Create a dummy = Node(0) and a tail pointer starting there.
  2. While both lists are non-empty: compare a.val and b.val, attach the smaller to tail.next, advance that list’s pointer and tail.
  3. Attach the non-empty remainder directly — no need to walk it.
  4. Return dummy.next.
a: 1 -> 3 -> 5
b: 2 -> 4 -> 6

dummy -> 1 -> 2 -> 3 -> 4 -> 5 -> 6

The dummy node means tail.next = smaller always works — no “is the result empty yet?” check.

Complexity

ValueWhy
TimeO(n + m)Each node visited exactly once
SpaceO(1)Rewiring existing nodes; only two extra pointers

Keep practising

All Coding Patterns questions

Explore further

Skip to content