CodeArchon

hardLinked ListAmazonFacebookGoogle

K-Way Chain Merger

A tournament coordinator pairwise merges k sorted standings into one grand leaderboard in O(N log k).

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

Choose approach

1
L0
4
5
1
L1
3
4
2
L2
6
nil
1/3
Narrationstep 1 of 3

Input: 3 sorted lists.

1def mergeKLists(lists):
2 if not lists: return None
3 while len(lists) > 1:
4 merged = []
5 for i in range(0, len(lists), 2):
6 a = lists[i]
7 b = lists[i + 1] if i + 1 < len(lists) else None
8 merged.append(mergeTwo(a, b))
9 lists = merged
10 return lists[0]
Variables
lists=3

How to think about it

  1. Alternative: min-heap of k heads with the same O(N log k) complexity.
  2. Pairwise merge has lower constant factor and avoids heap overhead.
  3. After round i the list count halves.

Edge cases to catch in interview

  • Empty input array → null.
  • Some lists empty → treated as [].

Examples

Example 1[1,1,2,3,4,4,5,6]
{"lists":[[1,4,5],[1,3,4],[2,6]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed