Skip to main content

25. Merge k Sorted Lists

hardAsked at Grab

Merge k sorted linked lists into one — Grab uses this to test heap + divide-conquer fluency.

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

Problem

You are given an array of k linked-lists lists, each linked-list is 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 <= total nodes <= 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. Concatenate and sort

Collect all values into an array, sort, then rebuild a list.

Time
O(N log N)
Space
O(N)
const all = [];
for (const l of lists) { let c = l; while (c) { all.push(c.val); c = c.next; } }
all.sort((a, b) => a - b);
// rebuild list

Tradeoff:

2. Min-heap of heads

Push each list's head into a min-heap; pop the smallest and push its next until the heap empties.

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 cur = dummy;
  while (heap.size()) {
    const node = heap.pop();
    cur.next = node;
    cur = cur.next;
    if (node.next) heap.push(node.next);
  }
  return dummy.next;
}

Tradeoff:

Grab-specific tips

Grab interviewers expect a heap-based merge for k-way streams — frame as merging per-region driver event logs into a single SEA-wide ordered stream.

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 Grab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →