Skip to question
SystemVerilogDesignVerificationFirmwareArchitectureASIC Interview Questions→
/Interview questions/Use lower-bound insertion for top-K largest

Q182·Free·SystemVerilog

Use lower-bound insertion for top-K largest

Difficulty
Medium
Topic
Data Structures
Language
SV
Interview prompt

Question

Keep the bounded top-K queue sorted and use binary search to locate each insertion position.

Candidate starting point

Implementation scaffold

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

// Implement here: Explain the required baseline and complexity comparison.

class TopKLargestBinary;
  int values[$]; // ascending, size <= k
  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 automatic int lower_bound(int x);
    int low = 0;
    int high = values.size();
    // Implement here: find the first position whose value is at least x.
  endfunction

  function void push(int x);
    int position;
    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 void snapshot_desc(ref int out[$]);
    // Implement here: replace out with a descending copy of the retained values.
  endfunction
endclass
Reviewed example

Trace one case

Input
K=3; ascending retained queue=[4,7,9]; insert(8)
Expected output
lower_bound(8)=2; retained queue=[7,8,9]

Binary search locates the insertion point, then the smallest of four candidates is removed to restore the K bound.

What to cover

Requirements

  1. Implement lower_bound(x) over an ascending queue.
  2. Insert every value while fewer than K observations are retained.
  3. Once full, ignore values no greater than the smallest retained value.
  4. Explain why binary search reduces comparisons but queue insertion still costs O(K).
Exact question handoffPractice Q182

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
  • Binary search
Firmware Guide →
Continue practicing

Related questions

Q176 · Data StructuresMaintain the K largest stream valuesMedium→Q214 · Data StructuresMaintain the top-K most frequent stream valuesMediumP→Q132 · Data StructuresReplace top-K sorting with frequency bucketsMedium→
ASIC.FYI · Learn silicon end to end.info@asic.fyi