Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Heaps & Priority Queues

K-way Merge

O(N log k)

Push the head of each list into a min-heap; repeatedly pop the smallest and push that list's next element.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn firstTop-K Elements
0%
mastery
0/8 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

k already-sorted lists/arrays/rows to combine, k-th smallest across them, smallest range covering all lists, or merging sorted generators.

  1. 1Brute force

    Concatenate and sort O(N log N).

  2. 2The observation

    Re-sorting already-sorted data: only the k heads compete.

  3. 3Why it works

    The min-heap holds exactly the smallest unconsumed element of every non-empty source, so its top is the global next.

Reach for it when

  • +Merge k sorted lists/arrays, or find the k-th smallest across sorted rows/columns.
  • +Smallest range covering one element from each of k lists.
  • +Generate a sorted sequence by repeatedly expanding a sorted frontier (ugly numbers, smallest sums).

Not when

  • ×Only two sorted listsuse Two-pointer merge, O(n), no heap
  • ×Sources aren't sorted; sorting them first may dominateuse Rethink the approach
  • ×Just the k-th value with a monotone count (sorted matrix, multiplication table)use Binary search on the answer, O(n log range)
  • ×k-th in a single unsorted arrayuse Quickselect
  • ×You reach for concatenate-and-sort: O(N log N), ignores order, needs all N in memory, fails on streamsuse Size-k heap, O(N log k)

Intuition

K-way merge combines k already-sorted lists/arrays into one sorted output — or finds the k-th smallest across them — without re-sorting everything. The engine is a min-heap of size k holding the current front of each list.

Read the full intuition

The rhythm: seed the heap with each list's first element. Repeatedly pop the global smallest (it's the next output) and push that list's next element. The heap always holds ≤ k candidates — one per list — so each of the N total elements costs O(log k): O(N log k) overall, beating O(N log N) of dumping everything and sorting, and it works on streams you can't fully hold.

Key idea

Many "k-th smallest in a sorted matrix" or "ugly number" problems are secretly k-way merges: the heap holds the frontier of what's reachable, you pop in sorted order, and push the successors.

Why it costs what it costs

Time O(N log k). each of the N total elements is pushed/popped once on a heap capped at k entries.

Space O(k). the heap holds at most one element per list (plus the output).

Practice

Next · Foundation

Merge Two Sorted Lists

Dummy head + compare heads.

0/8 solved
  • Merge Two Sorted ListsFoundationFoundationAmazon, MicrosoftEasy
  • Merge Sorted ArrayApply it · In place with buffer at the end.Apply itMeta, MicrosoftEasy
  • Merge k Sorted ListsOne change · k sources.One changeAmazon, MetaHard
  • Kth Smallest Element in a Sorted MatrixOne change · Rows are sources; stop at k.One changeAmazon, CitadelMedium
  • Find K Pairs with Smallest SumsBranches · Sources are implicit (pairs).BranchesCitadel, AmazonMedium
  • Ugly Number IIBranches · Merge generated streams with dedupe.BranchesAmazon, AdobeMedium
  • Super Ugly NumberAdvanced · k generated streams.AdvancedMedium
  • Smallest Range Covering Elements from K ListsMastery checkMastery checkGoogle, CitadelHard

Pitfalls

Classic bugs

  • !Heap of node payloads crashes on ties in Python/JS; push (val, i, node) with an index tiebreaker.
  • !After popping a front, push that list's successor or the merge stalls and drops elements.
  • !Seeding the heap with empty lists/nodes; guard if node.
  • !Linear min over k heads instead of a heap is O(N·k).
  • !Pushing all elements at once defeats the frontier; seed one per source.
  • !Merging generated streams (ugly numbers): skip duplicates or you emit the same value twice.

Looks like it, isn't

  • Median of Two Sorted Arrays needs Binary Search
    Why
    Merging is O(m + n); binary searching the partition is O(log min(m, n)). source ↗
  • Kth Smallest Element in a Sorted Matrix needs Binary Search on the Answer
    Why
    Heap works, but binary search on the value with a staircase count is often better.
Go deepervariants and techniques · 1 combinations · interviewer follow-ups · resources

Variants and techniques

  • Merge k listsHeap of list fronts; pop smallest, push its next. Merge k Sorted Lists.
  • k-th in sorted matrixHeap of (val,row,col) frontiers, pop k times. Kth Smallest in a Sorted Matrix.
  • Smallest k pairsHeap of candidate (i,j) sums, expand neighbours. Find K Pairs with Smallest Sums.
  • Smallest covering rangeHeap of k fronts; track current max; range = [min(front), curMax]. Smallest Range Covering Elements from K Lists.
  • Frontier generationHeap pops in sorted order, push multiplied successors. Ugly Number II, Super Ugly Number.

Combinations

  • K-way Merge+Binary Search on the Answer

    k-th smallest in a sorted matrix / sorted pair sums

    K-way Merge:
    frontier heap pops k times
    Binary Search on the Answer:
    alternatively binary search the value with a count

    Kth Smallest Element in a Sorted MatrixFind K Pairs with Smallest Sums

Follow-ups interviewers ask

  1. 01What if the lists are streams too large for memory? → the size-k heap already needs only O(k) memory; this is the classic external merge sort merge phase.
  2. 02What if k is huge (millions of lists)? → divide-and-conquer pairwise merge avoids a giant heap and parallelises well.
  3. 03Find the k-th smallest without materialising the merge? → stop after k pops, or binary-search the value.
  4. 04What if elements arrive out of order within a list? → it's no longer k-way merge; you'd need a full sort or different structure.

State table

pop heap (front vals) output
init {1, 2, 3} —
1 {4, 2, 3} 1
2 {4, 3} 1 2
3 {4, 5} 1 2 3
4 {5} 1 2 3 4
5 {} 1 2 3 4 5

Resources

  • Heap visualizerVisuAlgo · tool
  • Heap cheatsheetTech Interview Handbook · article
  • std::priority_queuecppreference · docs
  • Find Median from Data Stream editorialLeetCode · editorial
  • Heaps and Heap SortAbdul Bari · video
Two HeapsSubsets / Permutations / Combinations
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial