Q209FreeSystemVerilog
Maintain the K largest stream values
Interview prompt
Question
Continuously process integers and retain the K largest values seen so far, including duplicate occurrences.
Starting point
Question code
class TopKLargest;
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=3; stream=[4,9,1,9,7]Expected output
snapshot=[9,9,7]; get_kth()=7Duplicate observations are retained, and the bounded structure discards 4 and 1 as smaller than the final top three.
What to cover
Requirements
- Keep at most K real stream values rather than pre-filling the structure with sentinels.
- get_kth() returns the Kth largest value or the sentinel before K values have arrived.
- snapshot() returns retained values in descending order.
- Reject nonpositive K.

