LeetCode pattern lab · bounded priority

Keep the few.Reveal the best.

Stream every candidate through a capacity-K heap. Watch the boundary decide who enters, who leaves, and why sorting everything is unnecessary.

Problem deck

Choose what “best” means

Current mission

Kth Largest Element in an Array

Find the kth largest value without sorting the full array.

Medium
Steps14
Checkpoints5
Capacity2

Playback console

Control the stream

1 / 14

Choose a mission, set capacity K, then inspect the keeper heap.

Bounded heap arena

Configure the keeper heap

A min-heap keeps the weakest retained candidate visible at the root.

Capacity2
Stored0
Remaining6
Candidate streamprocessed 0 / 6
3value 3
2value 2
1value 1
5value 5
6value 6
4value 4

Keeper chamber

0 of 2 slots occupied

Heap waiting for candidates

RejectedNothing has crossed the boundary yet.

Live decision inspector

Which heap belongs at the boundary?

Min-heap · capacity 2
root = smallest kept

Next action

Stream candidates one at a time

The root must expose the easiest retained candidate to replace.

Invariant

The heap never stores more than k = 2 candidates.

Execution trace

Code in motion

def findKthLargest(nums, k):
heap = []
for value in nums:
heappush(heap, value)
if len(heap) > k:
heappop(heap)
return heap[0]

Why does this work?

Invariant laboratory

Predict which candidate crosses the boundary, then reveal the induction argument.

Local mastery

Your pattern record

Kth Largest Element in an Array0 runs0%
Top K Frequent Elements0 runs0%
K Closest Points to Origin0 runs0%

Completion and best checkpoint accuracy remain in this browser.

Stream in progress

The boundary is still deciding.

Complete the scan to record this mission. Prediction mastery requires at least 70% accuracy.

Recognize the pattern

When should you reach for a bounded heap?

Look for “largest,” “smallest,” “closest,” “most frequent,” or “best K” when K is much smaller than the full input. A heap avoids the cost and disruption of fully sorting candidates you will never return.

Can I score each candidate?
Do I need only K results?
Which retained item is weakest?
Can that weakest item live at the root?

Decision recipe

  1. 01Define the score and whether larger or smaller is better.
  2. 02Choose a root that exposes the weakest retained item.
  3. 03Keep heap size at most K; replace only when the boundary improves.
  4. 04Return the root for kth order statistics or all retained nodes for Top K.