Q150FreeSystemVerilog
Estimate stream frequencies with a Count-Min Sketch
Interview prompt
Question
Trade exact counts for bounded memory by implementing a Count-Min Sketch that updates and estimates integer frequencies.
Candidate starting point
Implementation scaffold
class CountMinSketch #(
parameter int WIDTH = 128,
parameter int DEPTH = 4
);
int unsigned counters[DEPTH][WIDTH];
function new();
if (WIDTH <= 0 || DEPTH <= 0)
$fatal(1, "WIDTH and DEPTH must be positive");
counters = '{default: 0};
endfunction
function automatic int unsigned hash_index(int x, int row);
int unsigned mixed;
mixed = int'(x) ^ (32'h9e37_79b9 * (row + 1));
mixed ^= mixed >> 16;
mixed *= 32'h85eb_ca6b;
mixed ^= mixed >> 13;
return mixed % WIDTH;
endfunction
function void push(int x);
int unsigned column;
// Implement here: update the state for one new observation.
endfunction
function int unsigned estimate(int x);
int unsigned column;
int unsigned minimum = 32'hffff_ffff;
// Implement here: return the minimum selected row counter.
endfunction
endclassReviewed example
Trace one case
Input
push(A) three times; push(B) once; estimate(A)Expected output
estimate(A) >= 3 and never below the true count 3Taking the minimum across hash rows limits collision inflation; saturating counters prevent wraparound undercounts.
What to cover
Requirements
- Maintain one fixed-width counter row for each distinct row-specific hash salt.
- push(x) increments one addressed counter in every row.
- estimate(x) returns the minimum addressed counter across rows.
- Assume each true per-key frequency is at most 32'hffff_ffff; saturate counters so wraparound cannot create an undercount within that bound.
