Skip to main content

Merge K Sorted Lists

Merge k sorted linked lists into one sorted linked list Example: [[1,4,5],[1,3,4],[2,6]] => [1,1,2,3,4,4,5,6]

You know how to merge two sorted lists—but what happens when there are k of them? Interviewers use this to see if you can scale your thinking and pick the right data structure for efficiency. The heap-based approach is elegant, but the real signal is how you reason about the tradeoffs.

Examples

You write

merge_k_lists(lists: List[Optional[ListNode]])

  1. Example 1

    Input
    [[1,4,5],[1,3,4],[2,6]]
    returns
    [1,1,2,3,4,4,5,6]
  2. Example 2

    Input
    []
    returns
    []

The pattern behind it

Linked Lists

I reach for it when

  • Nodes point to the next node, and you cannot index into the list.
  • You must reverse, merge, reorder or remove a node.

Say this before you type. Say which pointers you hold and which link you are about to change.

All 12 Linked Lists problems

Heaps

I reach for it when

  • You need the k largest or k smallest items.
  • You repeatedly take the best remaining item.

Say this before you type. Say what the heap holds, how big it stays, and what sits on top.

All 22 Heaps problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Merge K Sorted Listshard
2Part 2
3Part 3
4Part 4

Each locked part opens in the editor once the part before it passes.

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.