Q166FreeSystemVerilog
Replace top-K sorting with frequency buckets
Interview prompt
Question
Redesign the exact top-K frequency tracker so a query can walk frequency buckets instead of sorting every distinct key.
Starting point
Question code
class BucketTopKFrequent;
function new(int k, int sentinel = -1);
function void push(int x);
function int get_kth();
function int[$] snapshot();
endclassReviewed example
Trace one case
Input
K=2; stream=[2,3,2,3,1]Expected output
snapshot=[2,3] with frequencies [2,2]Both winners occupy frequency bucket two, and the ascending-value tie-break places 2 before 3.
What to cover
Requirements
- Keep one exact count and exactly one bucket membership for every value.
- On push(x), remove x from its old-frequency bucket and add it to the next bucket.
- Walk from the highest frequency downward until K values are collected.
- Break ties by ascending numeric value.

