Priority Detection Queue With Put and GetNext

Medium · Software Engineering Fundamentals · Backend Engineer · Technical Screen

Problem Statement

Implement an in-memory priority store DetectionStore that ingests security detection records via Put and dispatches them one at a time in priority order via GetNext.

Each detection record carries three fields:

  • unique_id: non-empty string key identifying the detection.
  • risk_score: unsigned 64-bit integer severity score (0 <= risk_score <= 2^64 - 1).
  • data: arbitrary payload string associated with the detection.

In C++, the target interface transfers exclusive ownership of each popped record via std::unique_ptr:

struct Detection {
    std::string unique_id;
    unsigned long risk_score;
    std::string data;
};

class DetectionStore {
public:
    void Put(const Detection& detection);
    std::unique_ptr<Detection> GetNext();
};

In Python, implement the store behind the batch replay function:

def detection_store(
    operations: List[str], arguments: List[List[str]]
) -> List[Optional[List[str]]]:

Ordering & Conflict Policies

In a live interview, you should clarify priority direction, tie-breaking, empty-queue behavior, and duplicate-ID updates before coding. Your implementation must enforce the following policies:

  1. Highest severity first: GetNext removes and returns the currently stored detection with the largest numeric risk_score (compared numerically, not lexicographically).
  2. FIFO tie-breaking: When multiple stored detections share the maximum risk_score, serve the one whose latest Put occurred earliest.
  3. Empty store: Calling GetNext when zero detections are waiting immediately returns None (nullptr in C++).
  4. In-place replacement on duplicate ID: If Put receives a unique_id that is still waiting in the store, it replaces that detection's risk_score, data, and arrival position (Put order) rather than keeping two copies. Once GetNext has removed a detection, its unique_id may be inserted again later as a brand-new arrival.

Batch Driver Contract

  • When operations[i] == "Put", arguments[i] is [unique_id, risk_score_str, data], where risk_score_str is the base-10 string form of risk_score. Store (or replace) the detection and append None to the output list.
  • When operations[i] == "GetNext", arguments[i] is []. Remove the highest-priority waiting detection and append [unique_id, str(risk_score), data], or append None if the store is empty.

Examples

Example 1

Input:
  operations = ["Put", "Put", "Put", "GetNext", "GetNext", "GetNext", "GetNext"]
  arguments = [
      ["evt-10", "40", "port-scan"],
      ["evt-20", "85", "ransomware"],
      ["evt-30", "40", "beacon"],
      [],
      [],
      [],
      [],
  ]
Output:
  [
      None,
      None,
      None,
      ["evt-20", "85", "ransomware"],
      ["evt-10", "40", "port-scan"],
      ["evt-30", "40", "beacon"],
      None,
  ]
  • The first GetNext pops "evt-20" because score 85 beats 40.
  • "evt-10" and "evt-30" tie at score 40, so FIFO order pops "evt-10" before "evt-30".
  • The fourth GetNext sees an empty store and returns None.

Example 2

Input:
  operations = ["Put", "Put", "Put", "GetNext", "GetNext"]
  arguments = [
      ["sig-1", "90", "initial"],
      ["sig-2", "60", "lateral-move"],
      ["sig-1", "25", "downgraded"],
      [],
      [],
  ]
Output:
  [
      None,
      None,
      None,
      ["sig-2", "60", "lateral-move"],
      ["sig-1", "25", "downgraded"],
  ]

The second Put for "sig-1" overwrites its earlier 90 score with 25 and payload "downgraded", so "sig-2" (60) is dispatched ahead of "sig-1" (25).

Constraints

  • 1 <= len(operations) == len(arguments) <= 10^4.
  • 0 <= int(risk_score_str) <= 2^64 - 1 (18,446,744,073,709,551,615).
  • Both Put and GetNext should run in logarithmic amortized time per operation with O(n) memory for n active detections.

Step-by-step walkthrough

  1. Clarify the contract and lock down the four open policies

    DetectionStore collects security detections (unique_id, risk_score, data) via Put and hands out the most urgent one via GetNext. The prompt deliberately leaves four behavior rules open so you ask clarifying questions in the interview. Let's state crisp, sensible policies up front — all consistent with the sample tests:

    1. Priority order: Higher risk_score is served first (Example 1 serves 85 ahead of 40).
    2. Tie-breaking: Detections with equal risk_score are served oldest-first (FIFO) so an older alert never gets jumped by newer alerts of the same score ("evt-10" before "evt-30").
    3. Empty store: GetNext returns None immediately (nullptr in C++), matching Example 1's fourth GetNext.
    4. Duplicate unique_id while still stored: A new Put with an already-waiting unique_id replaces the stored detection (updating its score, payload, and arrival position), because re-scored telemetry supersedes stale alerts. Once GetNext has popped and returned an alert, its unique_id can be inserted again as a fresh detection.

    The automated judge replays a sequence of "Put" and "GetNext" calls in Python:

    Call #   Operation   Arguments                         Return value
      0      "Put"       ["evt-10", "40", "port-scan"]  -> None
      1      "Put"       ["evt-20", "85", "ransomware"] -> None
      2      "Put"       ["evt-30", "40", "beacon"]     -> None
      3      "GetNext"   []                             -> ["evt-20", "85", "ransomware"]  (85 > 40)
      4      "GetNext"   []                             -> ["evt-10", "40", "port-scan"]   (FIFO tie)
      5      "GetNext"   []                             -> ["evt-30", "40", "beacon"]
      6      "GetNext"   []                             -> None                            (empty)
    
  2. Why a plain list is too slow, and how tuple keys order a heap

    If we store pending detections in an unsorted list, GetNext must scan all n detections to find the highest score (O(n)). If we keep a list sorted by score, GetNext pops from the end in O(1), but every Put must shift up to n elements to insert (O(n)).

    A binary heap (priority queue) keeps the highest-priority item at the root while supporting both push and pop in O(log n) time. Python's heapq module implements a min-heap (smallest item pops first), so we encode each detection as a 4-tuple with an increasing arrival counter seq:

    Heap tuple:  (-risk_score,  seq,  unique_id,  data)
                      ^          ^
                      |          +-- 2nd key: smaller seq = older Put wins ties (FIFO)
                      +------------- 1st key: larger risk_score becomes more negative -> pops first!
    

    Because every Put receives a strictly increasing seq (0, 1, 2, ...), two tuples can never tie on seq, so Python never even compares unique_id or data.

  3. Handle duplicate IDs in O(log n) with lazy deletion and compaction

    What happens when Put("x", 1, "new") arrives while ("x", 9, "old") is already sitting somewhere inside self.heap? Searching the heap to delete the old tuple would take O(n) time.

    Instead, we use lazy deletion with a dictionary self.live_seq that maps each currently stored unique_id to its latest seq:

    1. Put("x", 9, "old")  -> seq = 0, live_seq = {"x": 0}, heap = [(-9, 0, "x", "old")]
    2. Put("y", 5, "mid")  -> seq = 1, live_seq = {"x": 0, "y": 1}
    3. Put("x", 1, "new")  -> seq = 2, live_seq = {"x": 2, "y": 1}   <-- seq 0 for "x" is now STALE!
    4. GetNext():
         pop (-9, 0, "x", "old") -> live_seq.get("x") is 2 != 0 -> stale! Throw away and keep popping.
         pop (-5, 1, "y", "mid") -> live_seq.get("y") is 1 == 1 -> live! Delete "y" from live_seq, return it.
    

    Notice why we check self.live_seq.get(unique_id) == seq rather than unique_id in self.live_seq: "x" is still in live_seq, so only the seq number distinguishes the new "x" (seq = 2) from the stale "x" (seq = 0).

    One subtle edge case remains: what if "x" is updated 100,000 times with rising scores without calling GetNext? All 99,999 low-score stale tuples would sit at the bottom of self.heap holding old data strings in memory. Adding _compact_if_needed() — which filters self.heap down to live tuples and calls heapq.heapify whenever len(self.heap) > max(32, 2 * len(self.live_seq)) — costs O(1) amortized work per Put and guarantees total memory stays O(n) for n live detections.

  4. Implement DetectionStore in Python

    from typing import Dict, List, Optional, Tuple
    import heapq
    
    
    class DetectionStore:
        def __init__(self) -> None:
            # heap: min-heap of (-risk_score, seq, unique_id, data), e.g. (-85, 1, "evt-20", "ransomware").
            self.heap: List[Tuple[int, int, str, str]] = []
            # live_seq: maps unique_id -> latest `seq` currently active in the store, e.g. {"evt-20": 1}.
            self.live_seq: Dict[str, int] = {}
            # next_seq: monotonically increasing arrival counter (0, 1, 2, ...).
            self.next_seq: int = 0
    
        def _compact_if_needed(self) -> None:
            """Sweep out stale heap entries once they outnumber live ones, keeping space O(n)."""
            if len(self.heap) <= max(32, 2 * len(self.live_seq)):
                return
    
            live_entries: List[Tuple[int, int, str, str]] = []
            for entry in self.heap:
                seq = entry[1]
                unique_id = entry[2]
                if self.live_seq.get(unique_id) == seq:
                    live_entries.append(entry)
    
            heapq.heapify(live_entries)
            self.heap = live_entries
    
        def put(self, unique_id: str, risk_score: int, data: str) -> None:
            seq = self.next_seq
            self.next_seq += 1
    
            # Overwriting live_seq[unique_id] instantly marks any older heap entry for unique_id stale.
            self.live_seq[unique_id] = seq
            heapq.heappush(self.heap, (-risk_score, seq, unique_id, data))
            self._compact_if_needed()
    
        def get_next(self) -> Optional[Tuple[str, int, str]]:
            # Pop until we find an entry whose `seq` matches the latest live `seq` for its unique_id.
            while self.heap:
                neg_score, seq, unique_id, data = heapq.heappop(self.heap)
                if self.live_seq.get(unique_id) == seq:
                    # Deleting from live_seq frees unique_id so a future Put starts fresh.
                    del self.live_seq[unique_id]
                    return (unique_id, -neg_score, data)
                # Otherwise this entry was replaced by a newer Put; discard it and keep popping.
    
            return None
    
  5. Write the judge adapter and watch out for string scores

    In the judge input, args[1] is passed as a decimal string such as "9" or "100". We must convert it with int(args[1]) before pushing: if compared as strings, "9" > "100" because '9' comes after '1' in ASCII! Python's arbitrary-precision int also handles the full 64-bit unsigned long range (0 up to 18,446,744,073,709,551,615) with zero overflow risk.

    from typing import List, Optional
    
    
    def detection_store(
        operations: List[str], arguments: List[List[str]]
    ) -> List[Optional[List[str]]]:
        store = DetectionStore()
        results: List[Optional[List[str]]] = []
    
        for operation, args in zip(operations, arguments):
            if operation == "Put":
                unique_id = args[0]
                # Parse risk_score as int so "10" ranks above "9" (as strings, "9" > "10").
                risk_score = int(args[1])
                data = args[2]
                store.put(unique_id, risk_score, data)
                results.append(None)
            elif operation == "GetNext":
                detection = store.get_next()
                if detection is None:
                    results.append(None)
                else:
                    unique_id, risk_score, data = detection
                    results.append([unique_id, str(risk_score), data])
            else:
                raise ValueError(f"unknown operation: {operation}")
    
        return results
    
  6. Write the C++14 implementation with zero extra payload copies

    Because the original interview prompt asks for C++, pay attention to two C++-specific traps hinted at in the problem:

    1. Moving out of the heap (std::unique_ptr ownership): std::priority_queue::top() returns const T&, so std::move(pq.top()) silently invokes the copy constructor and duplicates data! Using std::vector<Entry> with std::push_heap and std::pop_heap moves the winning Entry to heap_.back(), where std::move(heap_.back()) transfers its strings into the std::unique_ptr<Detection> in O(1) without copying the payload buffer.
    2. Unsigned risk scores: risk_score is unsigned long, so -risk_score wraps around modulo 2^64 instead of turning negative. Instead, write a comparator ServedLater where ServedLater(a, b) returns true when a has lower priority than b (a.risk_score < b.risk_score, or equal scores with a.seq > b.seq).
    #include <algorithm>
    #include <cstddef>
    #include <memory>
    #include <string>
    #include <unordered_map>
    #include <utility>
    #include <vector>
    
    struct Detection {
        std::string unique_id;
        unsigned long risk_score;
        std::string data;
    };
    
    class DetectionStore {
    public:
        void Put(const Detection& detection) {
            const unsigned long long seq = next_seq_++;
            live_seq_[detection.unique_id] = seq;
            heap_.push_back(Entry{detection, seq});
            std::push_heap(heap_.begin(), heap_.end(), ServedLater{});
            CompactIfNeeded();
        }
    
        std::unique_ptr<Detection> GetNext() {
            while (!heap_.empty()) {
                // pop_heap moves the highest-priority entry to heap_.back() so we can move it out.
                std::pop_heap(heap_.begin(), heap_.end(), ServedLater{});
                Entry entry = std::move(heap_.back());
                heap_.pop_back();
    
                auto it = live_seq_.find(entry.detection.unique_id);
                if (it != live_seq_.end() && it->second == entry.seq) {
                    live_seq_.erase(it);
                    return std::make_unique<Detection>(std::move(entry.detection));
                }
            }
            return nullptr;
        }
    
    private:
        struct Entry {
            Detection detection;
            unsigned long long seq;
        };
    
        // std::push_heap puts the "greatest" element at front(), meaning ServedLater(front, child) == false.
        struct ServedLater {
            bool operator()(const Entry& a, const Entry& b) const {
                if (a.detection.risk_score != b.detection.risk_score) {
                    return a.detection.risk_score < b.detection.risk_score;
                }
                return a.seq > b.seq;
            }
        };
    
        void CompactIfNeeded() {
            const std::size_t threshold = std::max<std::size_t>(32, 2 * live_seq_.size());
            if (heap_.size() <= threshold) {
                return;
            }
            std::vector<Entry> live;
            live.reserve(live_seq_.size());
            for (Entry& entry : heap_) {
                auto it = live_seq_.find(entry.detection.unique_id);
                if (it != live_seq_.end() && it->second == entry.seq) {
                    live.push_back(std::move(entry));
                }
            }
            std::make_heap(live.begin(), live.end(), ServedLater{});
            heap_ = std::move(live);
        }
    
        std::vector<Entry> heap_;
        std::unordered_map<std::string, unsigned long long> live_seq_;
        unsigned long long next_seq_ = 0;
    };
    
  7. Trace Example 1 and Example 2

    Let's verify priority order, FIFO tie-breaking, and in-place replacement side by side:

    Example 1:
      Put("evt-10", 40, "port-scan")  -> seq=0, live_seq={"evt-10": 0}
      Put("evt-20", 85, "ransomware") -> seq=1, live_seq={"evt-10": 0, "evt-20": 1}
      Put("evt-30", 40, "beacon")     -> seq=2, live_seq={"evt-10": 0, "evt-20": 1, "evt-30": 2}
      GetNext()                       -> pops (-85, 1, "evt-20", ...) -> ["evt-20", "85", "ransomware"]
      GetNext()                       -> pops (-40, 0, "evt-10", ...) -> ["evt-10", "40", "port-scan"]
      GetNext()                       -> pops (-40, 2, "evt-30", ...) -> ["evt-30", "40", "beacon"]
      GetNext()                       -> heap is empty                -> None
    
    Example 2:
      Put("sig-1", 90, "initial")      -> seq=0, live_seq={"sig-1": 0}
      Put("sig-2", 60, "lateral-move") -> seq=1, live_seq={"sig-1": 0, "sig-2": 1}
      Put("sig-1", 25, "downgraded")   -> seq=2, live_seq={"sig-1": 2, "sig-2": 1} (seq=0 is now stale!)
      1st GetNext(): pops (-90, 0, "sig-1", "initial") [stale: 2 != 0],
                     then pops (-60, 1, "sig-2", "lateral-move") [live] -> ["sig-2", "60", "lateral-move"]
      2nd GetNext(): pops (-25, 2, "sig-1", "downgraded") [live: 2 == 2] -> ["sig-1", "25", "downgraded"]
    
  8. Complete solution

    Here is the complete Python solution for the automated judge:

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    # Chosen policies for the open design questions in the prompt:
    # 1. Priority: highest risk_score is served first.
    # 2. Tie-breaker: equal risk_score detections are served oldest-first (FIFO).
    # 3. Empty store: GetNext returns None immediately (nullptr in C++).
    # 4. Duplicate unique_id: Put replaces an unserved detection (new score, data, and arrival order).
    
    
    class DetectionStore:
        def __init__(self) -> None:
            # heap: min-heap of (-risk_score, seq, unique_id, data), e.g. (-85, 1, "evt-20", "ransomware").
            # Negating risk_score makes Python's min-heap pop the highest score first;
            # smaller `seq` breaks ties in FIFO arrival order without ever comparing `data`.
            self.heap: List[Tuple[int, int, str, str]] = []
            # live_seq: maps unique_id -> latest `seq` currently active in the store, e.g. {"evt-20": 1}.
            self.live_seq: Dict[str, int] = {}
            # next_seq: monotonically increasing arrival counter (0, 1, 2, ...).
            self.next_seq: int = 0
    
        def _compact_if_needed(self) -> None:
            """Sweep out stale heap entries once they outnumber live ones, keeping space O(n)."""
            if len(self.heap) <= max(32, 2 * len(self.live_seq)):
                return
    
            live_entries: List[Tuple[int, int, str, str]] = []
            for entry in self.heap:
                seq = entry[1]
                unique_id = entry[2]
                if self.live_seq.get(unique_id) == seq:
                    live_entries.append(entry)
    
            heapq.heapify(live_entries)
            self.heap = live_entries
    
        def put(self, unique_id: str, risk_score: int, data: str) -> None:
            seq = self.next_seq
            self.next_seq += 1
    
            # Overwriting live_seq[unique_id] instantly marks any older heap entry for unique_id stale.
            self.live_seq[unique_id] = seq
            heapq.heappush(self.heap, (-risk_score, seq, unique_id, data))
            self._compact_if_needed()
    
        def get_next(self) -> Optional[Tuple[str, int, str]]:
            # Pop until we find an entry whose `seq` matches the latest live `seq` for its unique_id.
            while self.heap:
                neg_score, seq, unique_id, data = heapq.heappop(self.heap)
                if self.live_seq.get(unique_id) == seq:
                    # Deleting from live_seq frees unique_id so a future Put starts fresh.
                    del self.live_seq[unique_id]
                    return (unique_id, -neg_score, data)
                # Otherwise this entry was replaced by a newer Put; discard it and keep popping.
    
            return None
    
    
    def detection_store(
        operations: List[str], arguments: List[List[str]]
    ) -> List[Optional[List[str]]]:
        store = DetectionStore()
        results: List[Optional[List[str]]] = []
    
        for operation, args in zip(operations, arguments):
            if operation == "Put":
                unique_id = args[0]
                # Parse risk_score as int so "10" ranks above "9" (as strings, "9" > "10").
                risk_score = int(args[1])
                data = args[2]
                store.put(unique_id, risk_score, data)
                results.append(None)
            elif operation == "GetNext":
                detection = store.get_next()
                if detection is None:
                    results.append(None)
                else:
                    unique_id, risk_score, data = detection
                    results.append([unique_id, str(risk_score), data])
            else:
                raise ValueError(f"unknown operation: {operation}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of DetectionStore as a hospital emergency-room triage desk for security alerts. Every arriving alert gets stamped with a severity score (risk_score) and a sequential ticket number (seq), then placed into a binary heap — a tree-in-an-array priority queue that always keeps the highest-priority item at the front while inserting or removing items in O(log n) steps. When an analyst calls GetNext, the desk serves the highest risk_score first, breaking ties by lowest ticket number (seq) for FIFO (first-in, first-out, meaning oldest arrival first) fairness. If an updated report arrives for an alert unique_id that is still waiting, we avoid hunting through the middle of the heap by using lazy deletion — recording only the newest ticket number per unique_id in a hash map (live_seq) and throwing away any outdated ticket if it later surfaces at the top of the heap.

Why do simpler data structures fall short? Keeping pending alerts in an unsorted list makes Put fast, but forces every GetNext to scan all n alerts in O(n) time to find the maximum score. Keeping a list sorted by score makes GetNext O(1) at the end, but forces every Put to shift up to n elements in O(n) time. Even with a heap, trying to eagerly search and remove an existing unique_id on duplicate Put degrades Put right back to O(n), whereas lazy deletion plus periodic compaction (rebuilding the heap from only live entries whenever stale entries outnumber live ones) keeps both operations logarithmic in n.

Let's trace Example 2 step by step:

1. Put("sig-1", 90, "initial")      -> seq=0 | live_seq={"sig-1": 0}
2. Put("sig-2", 60, "lateral-move") -> seq=1 | live_seq={"sig-1": 0, "sig-2": 1}
3. Put("sig-1", 25, "downgraded")   -> seq=2 | live_seq={"sig-1": 2, "sig-2": 1} (seq=0 is now stale)
4. GetNext():
   - pops (-90, 0, "sig-1", "initial"): live_seq.get("sig-1") is 2 != 0 -> stale, discard!
   - pops (-60, 1, "sig-2", "lateral-move"): live_seq.get("sig-2") is 1 == 1 -> live! Return "sig-2".
5. GetNext():
   - pops (-25, 2, "sig-1", "downgraded"): live_seq.get("sig-1") is 2 == 2 -> live! Return "sig-1".

Complexity

Let n be the number of live detections currently waiting in the store (plus payload copy cost O(|data|) on Put when copying const Detection& in C++).

  • Put — Amortized O(log n) time: Because _compact_if_needed keeps total heap size H <= max(32, 2n), heappush sifts up at most O(log n) levels and live_seq[unique_id] = seq is an O(1) average hash-map write. When compaction runs, heapify takes O(H) linear time after at least H / 2 stale-producing Put calls, charging O(1) amortized (averaged per operation over any worst-case sequence) work to each Put.
  • GetNext — Amortized O(log n) time: Each heappop costs O(log H) = O(log n) time. A single GetNext may skip several stale tuples, but every Put pushes only one tuple and each tuple can be popped at most once across the entire run.
  • Space — O(n): live_seq holds n entries, and compaction ensures self.heap never holds more than max(32, 2n) entries (plus the strings inside those entries).

Edge cases

  • Empty store (initially, after draining, or when only stale entries remain in the heap): GetNext pops any remaining stale tuples, exits the loop, and returns None (nullptr in C++).
  • Ties on risk_score: Broken strictly by arrival counter seq, not alphabetically by unique_id.
  • Replacing a stored unique_id: Updates score, payload, and seq (counting as a fresh arrival behind earlier equal-score detections) while invalidating the older heap entry.
  • Reusing a unique_id after GetNext served it: del self.live_seq[unique_id] cleans up the ID on pop so a later Put treats it as a new arrival.
  • 64-bit unsigned long boundaries (0 to 18,446,744,073,709,551,615): Handled cleanly by Python's unbounded int and by an unsigned-safe comparator in C++.
  • Repeated replacements with rising or falling scores: Falling scores surface at the heap top and are skipped in O(log n) amortized time; rising scores bury stale entries at the bottom until _compact_if_needed sweeps them out.

Common mistakes

  • Calling std::move(pq.top()) on std::priority_queue in C++: top() returns a const reference so mutating it cannot break the heap invariant; std::move on a const Detection& silently copies the Detection and its data string. Use std::vector + std::pop_heap and move from heap_.back() before calling pop_back(), and wrap the moved value in std::unique_ptr (a C++ smart pointer expressing exclusive ownership of a heap-allocated object).
  • Negating unsigned long in C++: -risk_score on an unsigned integer does modular wrap-around (-1UL becomes ULONG_MAX), scrambling priority order. Always use a comparator instead.
  • Comparing string scores without int(...) in the judge adapter: Lexicographically "9" > "20" > "100", which serves lower numeric scores ahead of higher ones.
  • Checking unique_id in self.live_seq instead of self.live_seq.get(unique_id) == seq: After an in-place replacement, unique_id is still in live_seq, so failing to match seq serves the outdated version!
  • Omitting seq from the Python heap tuple: Writing (-risk_score, unique_id, data) breaks ties alphabetically by unique_id, and if two tuples share both risk_score and unique_id, Python compares data (or crashes with TypeError on non-comparable payloads).

Alternative approaches

  • Balanced binary search tree + hash index (std::map + std::unordered_map in C++): Store detections in std::map<Key, Detection> ordered by (risk_score DESC, seq ASC), paired with unordered_map<string, iterator>. Put, GetNext (begin()), Update, and Remove all run in worst-case O(log n) time with zero stale entries (O(n) exact memory), at the cost of per-node heap allocations and pointer chasing compared to a contiguous std::vector heap.
  • Per-score FIFO buckets (O(1) time): If risk_score comes from a small bounded integer range such as 0..100, an array of 101 deques (plus a bitmask of non-empty buckets) supports O(1) Put and O(1) GetNext.

Follow-up questions

  • How would you synchronize concurrent producers and consumers, and support a timed blocking pop when the queue is empty? Protect the store with a std::mutex (a mutual-exclusion lock ensuring only one thread accesses the internal heap and map at a time) paired with a std::condition_variable (a synchronization primitive that puts waiting worker threads to sleep until notified). Put locks the mutex, inserts the detection, unlocks, and calls cv.notify_one(). GetNext(timeout) acquires a std::unique_lock and calls cv.wait_for(lock, timeout, predicate) where the predicate checks live_seq_.size() > 0 || closed_ — checking live_seq_.size() rather than !heap_.empty() is crucial because a heap holding only stale entries has nothing to serve, and using a predicate loop guards against spurious wakeups (OS wakeups that happen without a matching notification). Under extreme multi-core contention, you can shard into score bands while keeping unique_id routing consistent across bands.

cpp std::unique_ptr<Detection> GetNext(std::chrono::milliseconds timeout) { std::unique_lock<std::mutex> lock(mutex_); if (!ready_.wait_for(lock, timeout, [this] { return closed_ || store_.Size() > 0; })) { return nullptr; // Timed out with zero live detections } if (store_.Size() == 0) { return nullptr; // Store was closed while waiting } return store_.GetNext(); }

  • Suppose callers also need in-place score updates and explicit cancellations by ID—how would you adapt your internal structures and what are the time bounds? With our lazy-deletion heap, Remove(unique_id) simply deletes unique_id from live_seq in O(1) average time (and triggers _compact_if_needed if stale entries now dominate). To support Update(unique_id, new_score) without the caller resupplying data, store the payload once in payloads[unique_id] = data and push lightweight (-new_score, seq, unique_id) entries into the heap in O(log n) amortized time. If worst-case (non-amortized) O(log n) time and zero stale entries are required, switch to C++17 std::map<Key, Detection> + unordered_map<string, Key>, where map_.extract(old_key) re-keys the node in O(log n) without reallocating or copying data.
  • If high-severity alerts arrive continuously, lower-severity ones could wait indefinitely—how can you prevent starvation while keeping critical alerts fast? Prevent starvation (low-priority items waiting indefinitely behind a steady stream of higher-priority arrivals) with priority aging: define an item's effective priority at time now as risk_score + aging_rate * (now - arrival_time). Notice the algebraic trick when comparing two waiting items A and B at the same now: adding aging_rate * now shifts every waiting item equally and cancels out (score_A + rate * (now - t_A) > score_B + rate * (now - t_B) is identical to score_A - rate * t_A > score_B - rate * t_B), so you can compute a fixed static priority key score - aging_rate * arrival_time once at Put time without ever re-sorting the heap! To ensure aging never lets an old low-risk event jump ahead of a true emergency, split the store into two tiers: a strict top tier for risk_score >= CRITICAL_THRESHOLD that is always drained first, and an aged heap (or weighted fair share, such as serving 1 aged low-tier item every k pops) below that threshold.
  • How should the store behave if memory is capped at a fixed maximum capacity and a new alert arrives when full? First decide the backpressure policy (how a bounded system pushes back when producers outpace consumers) with stakeholders: (1) reject or spill to durable disk/Kafka so no security alert is silently lost, (2) block the producer thread on a not_full_ condition variable until GetNext frees a slot, or (3) evict the lowest-priority stored detection if the incoming alert has higher risk_score. Note that if replacement of an already-stored unique_id arrives while at capacity, it updates in place without increasing live count n. If policy (3) (evicting the minimum element) is chosen, a standard max-heap cannot find its minimum element in better than O(n) time, so you should switch to a balanced tree (std::map), a min-max heap (a single array heap supporting both O(log n) pop-max and O(log n) pop-min), or twin max/min heaps sharing live_seq lazy deletion — and always emit metrics/audit logs whenever an alert is evicted or spilled.

Follow-up questions

Similar questions

More Crowdstrike interview questions

All 8 Crowdstrike questions →