Skip to question
SystemVerilogDesignVerificationFirmwareArchitectureASIC Interview Questions→
/Interview questions/Maintain the K largest stream values

Q176·Free·SystemVerilog

Maintain the K largest stream values

Difficulty
Medium
Topic
Data Structures
Language
SV
Interview prompt

Question

Continuously process integers and retain the K largest values seen so far, including duplicate occurrences.

Candidate starting point

Implementation scaffold

// Implement here: Explain why the full predicate is captured before insertion.

typedef int int_queue_t[$];

class TopKLargest;
  int values[$]; // ascending, real observations only
  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;
  endfunction

  function void push(int x);
    int position = 0;
    bit full_before_insert;
    // Implement here: update the state for one new observation.
  endfunction

  function int get_kth();
    // Implement here: return the required kth value or sentinel.
  endfunction

  function int_queue_t snapshot();
    int out[$];
    // Implement here: return the required ordered snapshot.
  endfunction
endclass
Reviewed example

Trace one case

Input
K=3; stream=[4,9,1,9,7]
Expected output
snapshot=[9,9,7]; get_kth()=7

Duplicate observations are retained, and the bounded structure discards 4 and 1 as smaller than the final top three.

What to cover

Requirements

  1. Keep at most K real stream values rather than pre-filling the structure with sentinels.
  2. get_kth() returns the Kth largest value or the sentinel before K values have arrived.
  3. snapshot() returns retained values in descending order.
  4. Reject nonpositive K.
Exact question handoffPractice Q176

Solve it in the question bank, keep your progress, and reveal the reviewed solution when your access allows.

Open in question bank →
Solution accessEach time you open this Solution, one Practice Credit is used; it is not permanently unlocked. Premium Solution content also uses one credit per opening.
Continue learning

Firmware Guide

Review algorithms, data structures, fixed-memory reasoning, concurrency, and silicon bring-up.

  • Data Structures
  • SystemVerilog
  • Top K
  • Sorted queue
Firmware Guide →
Continue practicing

Related questions

Q182 · Data StructuresUse lower-bound insertion for top-K largestMedium→Q214 · Data StructuresMaintain the top-K most frequent stream valuesMediumP→Q071 · Data StructuresDynamic arrays and queuesEasy→Q219 · Data StructuresQueue methodsEasyP→Q094 · Data StructuresImplement a simple least-recently-used cacheMedium→
ASIC.FYI · Learn silicon end to end.info@asic.fyi