FFORGE//RS
← Roadmap

rust / LEVEL 3

Top K without sorting the world

EST.40 MIN
01

THEORY / RETRIEVAL

What to restore

  • Count values before maintaining a bounded heap
  • Model a min-heap with BinaryHeap and Reverse
  • Return stable frequency-descending, value-ascending output

Top K needs only K live candidates

After counting U unique values, a min-heap of size K keeps the weakest current winner at its root. Each candidate costs O(log K), avoiding an O(U log U) full sort when K is small. Final K results are then sorted for the public output contract.

Tie-breaking belongs in the ordering type

Rust's `BinaryHeap` is a max-heap. `Reverse` can invert tuple ordering, but every tuple field participates. Here lower frequency is worse, and for equal frequency the larger numeric value is worse because output prefers smaller values.

CHECKPOINT

For U unique values and K requested winners, what is the bounded-heap complexity after counting?

ISOLATED RUST 1.96
src/lib.rsEDIT

02 / IMPLEMENTATION

Implement the contract

Return up to k (value, frequency) pairs ordered by frequency descending and value ascending. Use a heap bounded by k after counting; k=0 returns empty and k greater than the unique count returns every value.

Initializing editor…
CLOUD SANDBOXnetwork off · 256 MB · 12 s
1 / 64 KB
OUTPUT
Runner is waiting for a submission.