Skip to content

Merge Two Sorted Lists

EasyLeetCode #21Time O(n + m)Space O(1)

You get the heads of two linked lists, each sorted in ascending order. Join them into one sorted list by reusing their existing nodes, and return its head.

[1, 2, 4] and [1, 3, 4] -> [1, 1, 2, 3, 4, 4]

The smallest remaining value is always at the front of one of the two lists, so you only ever compare two nodes. This is the merge step of merge sort.

Keep a tail pointer to the end of the list you are building. Repeatedly attach the smaller front node to tail and advance that list. The awkward part is the very first node: which list does the result start with? A dummy head removes the question. You build after the dummy and return dummy.next. When one list runs out, the other is already sorted, so attach it in one step.

Show solutionHide solution
def merge_two_lists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = tail = ListNode() # dummy head: no special case for the first node
while list1 and list2:
if list2.val < list1.val:
list1, list2 = list2, list1 # keep the smaller node in list1
tail.next = list1
tail = list1
list1 = list1.next
tail.next = list1 or list2 # splice on whatever remains
return dummy.next
  • Time: O(n + m) — each node is attached exactly once.
  • Space: O(1) — you relink existing nodes and allocate only the dummy. (A recursive version is O(n + m) because of the call stack.)
  • Forgetting the leftover. After the loop one list is empty and the other may still have nodes. Attach it with tail.next = list1 or list2.
  • Returning dummy instead of dummy.next.
  • Empty inputs. If both are empty the loop is skipped and you return None. If one is empty the leftover step handles it.
  • Don’t create new nodes. It works but wastes O(n + m) space and misses the point.

Merge k sorted lists. The trick: keep the k current heads in a min-heap, pop the smallest, attach it, and push its successor. O(N log k) for N total nodes. Or merge pairs of lists repeatedly, halving the count each round.

Sort a linked list in O(n log n) time. The trick: merge sort. Split at the middle found with fast and slow pointers, sort each half recursively, and merge them with this exact function.

Merge two sorted arrays, where the first has spare space at its end. The trick: the same merge, but fill from the back so you never overwrite values you still need.