InterviewPrepKit

Home / Coding / Linked List

Merge k Sorted Lists

hard Original ↗
Solving tips
  • The next output node is the min of k current heads; a size-k min-heap gives it in O(log k) for O(N log k) total, beating the O(N*k) all-heads scan.
  • In Python push tuples (val, index, node) since ListNodes aren't comparable; the unique index breaks value ties before the comparison reaches the node.
  • Alternative same-bound approach: divide-and-conquer pairwise merging (merge lists 1&2, 3&4, ...) halves the count each round for log k rounds, O(1) extra space.
  • Avoid folding lists one-at-a-time into an accumulator (O(N*k), re-walks early nodes); handle empty lists and lists = [] as real test cases.

Problem

You are given an array of k linked lists, each already sorted in ascending order. Combine all of them into a single sorted linked list and return its head.

Some of the k lists may be empty, and the array itself may be empty. Total node count across all lists is what matters for performance — call it N. Merging two sorted lists is a classic easy problem; the point here is doing it for k lists without paying more than necessary.

Examples

  • Input: lists = [[1, 4, 5], [1, 3, 4], [2, 6]] → Output: [1, 1, 2, 3, 4, 4, 5, 6] All eight nodes interleaved into one ascending list.
  • Input: lists = [] → Output: [] No lists at all — the result is empty.
  • Input: lists = [[], [0]] → Output: [0] Empty lists contribute nothing and must not crash anything.

Constraints

  • k is in [0, 10^4], each list has up to 500 nodes, total N up to about 5 * 10^5 in practice.
  • -10^4 <= Node.val <= 10^4; each input list is sorted ascending.
  • The bound that matters: with k up to 10^4, an O(N * k) approach (comparing all k heads for every output node, or merging lists into the result one at a time) is too slow — the target is O(N log k).

Think about it first

Hint 1 At every step, the next output node is the smallest among the current heads of the k lists. How do you repeatedly extract the minimum of k changing candidates faster than scanning all k each time?
Hint 2 A min-heap of size k gives you the smallest head in O(log k). Pop a node, append it to the output, and push that node's successor — every node enters and leaves the heap exactly once.
Hint 3 Alternative with the same O(N log k) bound and O(1) heap-free space: divide and conquer. Merge lists in pairs (1 with 2, 3 with 4, …), halving the count each round; after log k rounds one list remains, and each round touches every node once.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.