Skip to main content

23. Merge k Sorted Lists

hardAsked at Postman

Merge k sorted linked lists into a single sorted list.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

You are given an array of k linked-lists, each sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.

Constraints

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= sum of list lengths <= 10^4

Examples

Example 1

Input
lists = [[1,4,5],[1,3,4],[2,6]]
Output
[1,1,2,3,4,4,5,6]

Example 2

Input
lists = []
Output
[]

Approaches

1. Pairwise sequential merge

Repeatedly merge list 0 with list 1, result with list 2, etc.

Time
O(kN)
Space
O(1)
let head = null;
for (const l of lists) head = merge(head, l);

Tradeoff:

2. Min-heap of heads

Push all list heads into a min-heap keyed by value; pop the smallest, append it, push its next.

Time
O(N log k)
Space
O(k)
function mergeKLists(lists) {
  const heap = new MinHeap((a, b) => a.val - b.val);
  for (const l of lists) if (l) heap.push(l);
  const dummy = { next: null };
  let tail = dummy;
  while (heap.size()) {
    const n = heap.pop();
    tail.next = n; tail = n;
    if (n.next) heap.push(n.next);
  }
  return dummy.next;
}
// MinHeap: standard binary heap with push, pop, size

Tradeoff:

Postman-specific tips

Postman uses k-way merge in the Newman run-aggregator that streams results from parallel test runs — the heap-of-heads pattern is exactly what they expect verbalized.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Merge k Sorted Lists and other Postman interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →