Skip to main content

LeetCode Patterns

K-way Merge Pattern

K-way Merge combines K sorted lists or sequences into a single sorted output by maintaining a min-heap of the current head element from each list and repeatedly popping the smallest. It generalizes the two-way merge of merge sort to any number of inputs in O(N log K) time, where N is the total number of elements and K is the number of lists.

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

Complexity

Time
O(N log K)
Space
O(K)

When to use K-way Merge

  • You need to merge K already-sorted lists, arrays, or linked lists into one sorted output.
  • You need to find the smallest range that contains at least one element from each of K sorted lists.
  • You need the kth smallest pair sum (or product) drawn from two sorted arrays.
  • You need to find a specific position in the union of several sorted streams without materializing the full union.
  • You can move forward in each input one element at a time without going back (no random access needed).

Template

function mergeKSortedLists(lists) {
  const heap = new MinHeap();
  for (let i = 0; i < lists.length; i++) {
    if (lists[i] !== null) {
      heap.push([lists[i].val, i, lists[i]]);
    }
  }
  const dummy = { val: 0, next: null };
  let tail = dummy;
  while (heap.size > 0) {
    const [, , node] = heap.pop();
    tail.next = node;
    tail = node;
    if (node.next !== null) heap.push([node.next.val, 0, node.next]);
  }
  return dummy.next;
}

Example LeetCode problems

#ProblemDifficultyFrequency
23Merge k Sorted Listshardcompany favorite
378Kth Smallest Element in a Sorted Matrixmediumfrequently asked
632Smallest Range Covering Elements from K Listshardclassic
373Find K Pairs with Smallest Sumsmediumfrequently asked
264Ugly Number IImediumclassic
313Super Ugly Numbermediumless common

Common mistakes

  • Forgetting to include a tiebreaker in the heap entry — when two heads have equal values, comparing the raw objects causes a runtime error in many languages.
  • Pushing every element of every list into the heap upfront, which costs O(N log N) space and time instead of O(N log K).
  • Not advancing the pointer in the source list after popping the head; the algorithm stalls because every pop pushes the same element back.
  • Using a max-heap by accident (e.g. reversed comparator) and returning elements in the wrong order.
  • Returning `dummy` instead of `dummy.next` and exposing the placeholder node to the caller.

Frequently asked questions

Why is K-way Merge faster than concatenating and sorting?

Concatenating costs O(N) and sorting costs O(N log N). K-way Merge runs in O(N log K), and K is almost always much smaller than N. For 1M elements across 10 lists, that is 1M*log(10) ≈ 3.3M operations vs 1M*log(1M) ≈ 20M.

Can I do K-way Merge without a heap?

You can divide-and-conquer: recursively merge pairs of lists. The complexity is the same — O(N log K) — but the divide-and-conquer version uses O(log K) stack space and can be easier to implement when a heap data structure is not available.

How does this pattern apply to a sorted matrix?

Treat each row as a sorted list and K-way merge them. To find the kth smallest, pop k times. Many problems combine this with binary search on the answer value when k is very large.

What is the smallest-range problem really asking?

Given K sorted arrays, find the smallest interval [a, b] such that at least one element of every array falls inside it. K-way Merge naturally tracks one element per list at a time; you maintain the running max while popping the running min, and the difference is a candidate range.

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 the K-way Merge pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →