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

Top-K Elements

O(n log k)

Keep a heap of size k (min-heap for k-largest), pushing and popping so only the k best ever survive.

  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
UnlocksTwo HeapsK-way MergeDijkstra (Weighted Shortest Path)Sweep Line (events + active set)+2
0%
mastery
0/29 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

"k largest / smallest / most frequent / closest", "the k-th ...", top-k of a stream, or repeatedly pick the min/max as items change.

  1. 1Brute force

    Sort everything O(n log n) per query.

  2. 2The observation

    Full sorting: only the best k (or the single current best) needs ordering.

  3. 3Why it works

    The heap holds exactly the best k seen so far and its root is the k-th best; each arrival is one O(log k) compare-and-evict.

Reach for it when

  • +Prompt says 'k largest / smallest / closest / most frequent' or 'the k-th …'.
  • +You need the top-k of a stream or a huge array without fully sorting it.
  • +You repeatedly need the current min/max while inserting — scheduling, merging, Dijkstra.

Not when

  • ×You need everything fully sorted anyway, or k is close to nuse Just sort
  • ×Frequencies or values are bounded small integers (<= n)use Bucket sort by frequency, O(n)
  • ×One k-th element of a static array, and reordering it is fineuse Quickselect, O(n) average
  • ×You need arbitrary deletion or ordered iterationuse Ordered set
  • ×You need a running median, i.e. both halves at onceuse Two heaps
  • ×You think k largest needs a max-heap of all n: that's O(n) space and can't streamuse Size-k min-heap

Intuition

A heap (priority queue) is a bucket that always hands you its smallest item (a min-heap) or largest (a max-heap) in O(log n), and lets you toss new items in for O(log n). You never see it sorted — you just trust that peek is the extreme and pop removes it. Picture a tournament bracket that re-settles itself after every insert so the champion is always on top.

Read the full intuition

The counter-intuitive trick for "k largest": use a min-heap of size k. Keep only k elements; whenever it overflows, pop the smallest. What survives is the k biggest, and the heap's top is the k-th largest. (For "k smallest", mirror it with a max-heap.)

Why size k and not n? Because you only ever need to remember the best k so far. Each of n elements costs O(log k), giving O(n log k) — better than sorting everything (O(n log n)) when k is small, and it works on a stream where you can't hold all n.

Walk "2nd largest" over [3, 1, 5, 2, 4], k=2, min-heap:

  • push 3 → [3]; push 1 → [1,3].
  • 5: push → [1,3,5], size>2 → pop 1 → [3,5].
  • 2: 2 < top(3), skip (can't be in top 2).
  • 4: push → [3,4,5], pop 3 → [4,5]. Top = 4 = 2nd largest. ✓

Python's heapq is a min-heap only. For a max-heap, push negatives (-x) and negate on the way out.

Why it costs what it costs

Time O(n log k). each of n elements does at most one push+pop on a heap capped at size k, costing O(log k).

Space O(k). the heap never holds more than k elements (plus a frequency map for the frequency variants).

Practice

Next · Foundation

Kth Largest Element in a Stream

A size-k MIN-heap's root is the answer.

0/29 solved
  • Kth Largest Element in a StreamFoundationFoundationAmazon, StripeEasy
  • Last Stone WeightApply it · Repeatedly take the two largest.Apply itAmazon, AdobeEasy
  • K Closest Points to OriginOne change · Key is a computed distance.One changeMeta, AmazonMedium
  • Top K Frequent ElementsOne change · Count then select.One changeAmazon, MetaMedium
  • Kth Largest Element in an ArrayTwists · One-off query on a full array.TwistsMeta, AmazonMedium
  • Reorganize StringBranches · Greedy with a heap: take the most frequent that is not the previous.BranchesAmazon, MetaMedium
  • Single-Threaded CPUCombine · Sort by arrival + heap by processing time.CombineUber, AmazonMedium
  • Furthest Building You Can ReachMastery checkMastery checkGoogle, UberMedium
  • Meeting Rooms IIPremiumMedium
  • Task SchedulerMeta, AmazonMedium
  • IPOCitadel, Goldman SachsHard
  • The Skyline ProblemGoogle, AmazonHard

Pitfalls

Classic bugs

  • !Python heapq is min-only: forgetting to negate for a max-heap silently returns the wrong extreme.
  • !Heap grows to size n instead of being capped at k: you lose the O(n log k) time and O(k) space.
  • !k largest needs a min-heap so you can pop the weakest survivor. It feels backwards; it isn't.
  • !Python tuple ties: (-count, item) compares item on ties. Make it comparable or add an index tiebreaker.
  • !n pushes to build is O(n log n); with all elements upfront, heapify is O(n).

Looks like it, isn't

  • Task Scheduler needs Greedy
    Why
    A heap simulation works, but a counting formula on the max frequency gives O(n). source ↗
  • Last Stone Weight II needs 0/1 Knapsack
    Why
    Its sibling last-stone-weight is a heap simulation, but greedy smashing is not optimal here. Every outcome is |S1 - S2| for some split, so find the subset sum closest to total/2. source ↗
Go deepervariants and techniques · 7 combinations · interviewer follow-ups · resources

Variants and techniques

  • Bucket / Counting SortDistribute items into buckets by a bounded key (frequency, value range) so ordering is O(n + range) instead of O(n log n).
  • QuickselectPartition around a pivot and recurse into the side containing index k, giving expected O(n) for the k-th smallest.
  • Top-k by valueSize-k min-heap of raw values; survivors are the k largest. Kth Largest in an Array/Stream.
  • Top-k by frequencyCount first, then heap (or bucket) on counts. Top K Frequent, Sort Characters By Frequency.
  • K closestHeap on a distance key; size-k max-heap keeps the closest k. K Closest Points to Origin.
  • Repeated extremes / simulationMax-heap you keep popping and pushing back. Last Stone Weight, IPO.
  • Quickselect alternativeFor a static array, Hoare partition finds the k-th in O(n) average — faster but trickier than a heap.

Combinations

  • Greedy+Top-K Elements

    repeatedly pick the most frequent/cheapest/available item; time-based simulation

    Greedy:
    decides which item to take next
    Top-K Elements:
    retrieves the current best item in O(log n)

    Reorganize StringSingle-Threaded CPUTask Scheduler

  • Merge Intervals+Top-K Elements

    minimum rooms/machines; assign rooms to customers

    Merge Intervals:
    sort by start
    Top-K Elements:
    min-heap of end times of active intervals

    Meeting Rooms IIRoom Allocation

  • Sweep Line (events + active set)+Top-K Elements

    skyline / max active value over time

    Sweep Line (events + active set):
    processes building edges in x order
    Top-K Elements:
    max-heap (with lazy deletion) of active heights

    The Skyline Problem

  • Topological Sort+Top-K Elements

    lexicographically smallest topological order; 'course 1 as early as possible'

    Topological Sort:
    dependency order
    Top-K Elements:
    priority among available vertices

    Course Schedule II

  • Greedy with a Heap (regret / exchange later)+Top-K Elements

    survive constraints over time (health, bricks), maximise count taken

    Greedy with a Heap (regret / exchange later):
    take greedily, undo the worst past choice when a constraint breaks
    Top-K Elements:
    min-heap of taken items

    Furthest Building You Can ReachPotions (Hard Version)Buy Low Sell High

  • Slope Trick+Top-K Elements

    minimum total |change| to make an array non-decreasing, with large values

    Slope Trick:
    represent the cost function by its breakpoints
    Top-K Elements:
    a max-heap holds the breakpoints left of the minimum

    Increasing Array IISonya and Problem Wihtout a LegendSequence

  • Exchange-Argument Sorting (custom comparator)+Top-K Elements

    choose exactly a items for role A and b items for role B, maximising the total

    Exchange-Argument Sorting (custom comparator):
    sort by a_i - b_i so some prefix goes to group A and the rest to group B
    Top-K Elements:
    a heap keeps the best a values in the prefix and the best b values in the suffix

    Programmers and Artists

Follow-ups interviewers ask

  1. 01What if it's an infinite stream? → the size-k heap already runs online in O(k) memory — that's its whole point.
  2. 02k ≈ n? → a heap loses its edge; just sort (O(n log n)), or Quickselect for an O(n)-average k-th.
  3. 03Top-k by frequency? → count first, then heap or bucket sort by frequency for O(n).
  4. 04Need the k-th exactly, not all k? → Quickselect average O(n) beats the heap's O(n log k).

State table

x push → heap size>k? pop heap (k=2)
3 [3] — [3]
1 [1,3] — [1,3]
5 [1,3,5] pop 1 [3,5]
2 [2,3,5] pop 2 [3,5]
4 [3,4,5] pop 3 [4,5] → top 4 = 2nd largest

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
Binary Search on the AnswerTwo Heaps
TodayReviewPatternsProblems

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

Start the free 7-day trial