Skip to question
SystemVerilogDesignVerificationFirmwareArchitectureASIC Interview Questions→
/Interview questions/Replace top-K sorting with frequency buckets

Q132·Free·SystemVerilog

Replace top-K sorting with frequency buckets

Difficulty
Medium
Topic
Data Structures
Language
SV
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
endclass
Reviewed 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

  1. Keep one exact count and exactly one bucket membership for every value.
  2. On push(x), remove x from its old-frequency bucket and add it to the next bucket.
  3. Walk from the highest frequency downward until K values are collected.
  4. Break ties by ascending numeric value.
  5. 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.
Exact question handoffPractice Q132

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
  • Bucket sort
Firmware Guide →
Continue practicing

Related questions

Q214 · Data StructuresMaintain the top-K most frequent stream valuesMediumP→Q145 · Data StructuresTrack top-K frequencies in a sliding windowMedium→Q078 · Streaming AlgorithmsReport the top-K opcode frequenciesMedium→Q150 · Data StructuresEstimate stream frequencies with a Count-Min SketchMedium→
ASIC.FYI · Learn silicon end to end.info@asic.fyi