Q132FreeSystemVerilog
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.
Candidate starting point
Implementation scaffold
typedef int int_queue_t[$];
class BucketTopKFrequent;
int count_by_value[int];
bit member_by_frequency[int][int];
int max_frequency = 0;
int k;
int sentinel;
function new(int k, int sentinel = -1);
if (k <= 0) $fatal(1, "k must be positive");
this.k = k;
this.sentinel = sentinel;
max_frequency = 0;
endfunction
function void push(int x);
int old_frequency;
int new_frequency;
// Implement here: update the state for one new observation.
endfunction
function int_queue_t snapshot();
int out[$];
// Implement here: return the required ordered snapshot.
endfunction
function int get_kth();
int out[$];
// Implement here: return the required kth value or sentinel.
endfunction
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.
- K is positive. For each distinct value, the total number of push calls is at most 2,147,483,647 during the lifetime of this tracker, so its exact signed 32-bit frequency is representable.
