Skip to main content

25. Merge k Sorted Lists

hardAsked at Adyen

Merge k sorted linked lists into one sorted list.

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 <= lists[i].length <= 500
  • 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. Collect and sort

Flatten all values, sort, rebuild a list.

Time
O(N log N)
Space
O(N)
const vals = [];
for (const h of lists) { let c = h; while (c) { vals.push(c.val); c = c.next; } }
vals.sort((a,b)=>a-b);
const dummy = { next: null }; let tail = dummy;
for (const v of vals) { tail.next = { val: v, next: null }; tail = tail.next; }
return dummy.next;

Tradeoff:

2. Pairwise merge tournament

Repeatedly merge pairs of lists, halving the field each round.

Time
O(N log k)
Space
O(1)
function merge(a, b) {
  const d = { next: null }; let t = d;
  while (a && b) { if (a.val <= b.val) { t.next = a; a = a.next; } else { t.next = b; b = b.next; } t = t.next; }
  t.next = a || b;
  return d.next;
}
function mergeKLists(lists) {
  if (!lists.length) return null;
  while (lists.length > 1) {
    const next = [];
    for (let i = 0; i < lists.length; i += 2) next.push(merge(lists[i], lists[i+1] || null));
    lists = next;
  }
  return lists[0];
}

Tradeoff:

Adyen-specific tips

Adyen frames this as merging per-acquirer settlement streams — they want the O(N log k) tournament merge so multi-currency reconciliation stays predictable under load.

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

Practice these live with InterviewChamp.AI →