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:
- Highest severity first:
GetNextremoves and returns the currently stored detection with the largest numericrisk_score(compared numerically, not lexicographically). - FIFO tie-breaking: When multiple stored detections share the maximum
risk_score, serve the one whose latestPutoccurred earliest. - Empty store: Calling
GetNextwhen zero detections are waiting immediately returnsNone(nullptrin C++). - In-place replacement on duplicate ID: If
Putreceives aunique_idthat is still waiting in the store, it replaces that detection'srisk_score,data, and arrival position (Putorder) rather than keeping two copies. OnceGetNexthas removed a detection, itsunique_idmay 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], whererisk_score_stris the base-10 string form ofrisk_score. Store (or replace) the detection and appendNoneto 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 appendNoneif 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
GetNextpops"evt-20"because score85beats40. "evt-10"and"evt-30"tie at score40, so FIFO order pops"evt-10"before"evt-30".- The fourth
GetNextsees an empty store and returnsNone.
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
PutandGetNextshould run in logarithmic amortized time per operation withO(n)memory fornactive detections.
Step-by-step walkthrough
Clarify the contract and lock down the four open policies
DetectionStorecollects security detections (unique_id,risk_score,data) viaPutand hands out the most urgent one viaGetNext. 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:- Priority order: Higher
risk_scoreis served first (Example 1 serves85ahead of40). - Tie-breaking: Detections with equal
risk_scoreare served oldest-first (FIFO) so an older alert never gets jumped by newer alerts of the same score ("evt-10"before"evt-30"). - Empty store:
GetNextreturnsNoneimmediately (nullptrin C++), matching Example 1's fourthGetNext. - Duplicate
unique_idwhile still stored: A newPutwith an already-waitingunique_idreplaces the stored detection (updating its score, payload, and arrival position), because re-scored telemetry supersedes stale alerts. OnceGetNexthas popped and returned an alert, itsunique_idcan 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)- Priority order: Higher
Why a plain list is too slow, and how tuple keys order a heap
If we store pending detections in an unsorted list,
GetNextmust scan allndetections to find the highest score (O(n)). If we keep a list sorted by score,GetNextpops from the end inO(1), but everyPutmust shift up tonelements 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'sheapqmodule implements a min-heap (smallest item pops first), so we encode each detection as a 4-tuple with an increasing arrival counterseq: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
Putreceives a strictly increasingseq(0, 1, 2, ...), two tuples can never tie onseq, so Python never even comparesunique_idordata.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 insideself.heap? Searching the heap to delete the old tuple would takeO(n)time.Instead, we use lazy deletion with a dictionary
self.live_seqthat maps each currently storedunique_idto its latestseq: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) == seqrather thanunique_id in self.live_seq:"x"is still inlive_seq, so only theseqnumber 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 callingGetNext? All 99,999 low-score stale tuples would sit at the bottom ofself.heapholding olddatastrings in memory. Adding_compact_if_needed()— which filtersself.heapdown to live tuples and callsheapq.heapifywheneverlen(self.heap) > max(32, 2 * len(self.live_seq))— costsO(1)amortized work perPutand guarantees total memory staysO(n)fornlive detections.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 NoneWrite 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 withint(args[1])before pushing: if compared as strings,"9" > "100"because'9'comes after'1'in ASCII! Python's arbitrary-precisionintalso handles the full 64-bitunsigned longrange (0up to18,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 resultsWrite 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:
- Moving out of the heap (
std::unique_ptrownership):std::priority_queue::top()returnsconst T&, sostd::move(pq.top())silently invokes the copy constructor and duplicatesdata! Usingstd::vector<Entry>withstd::push_heapandstd::pop_heapmoves the winningEntrytoheap_.back(), wherestd::move(heap_.back())transfers its strings into thestd::unique_ptr<Detection>inO(1)without copying the payload buffer. - Unsigned risk scores:
risk_scoreisunsigned long, so-risk_scorewraps around modulo2^64instead of turning negative. Instead, write a comparatorServedLaterwhereServedLater(a, b)returnstruewhenahas lower priority thanb(a.risk_score < b.risk_score, or equal scores witha.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; };- Moving out of the heap (
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"]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— AmortizedO(log n)time: Because_compact_if_neededkeeps total heap sizeH <= max(32, 2n),heappushsifts up at mostO(log n)levels andlive_seq[unique_id] = seqis anO(1)average hash-map write. When compaction runs,heapifytakesO(H)linear time after at leastH / 2stale-producingPutcalls, chargingO(1)amortized (averaged per operation over any worst-case sequence) work to eachPut.GetNext— AmortizedO(log n)time: EachheappopcostsO(log H) = O(log n)time. A singleGetNextmay skip several stale tuples, but everyPutpushes only one tuple and each tuple can be popped at most once across the entire run.- Space —
O(n):live_seqholdsnentries, and compaction ensuresself.heapnever holds more thanmax(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):
GetNextpops any remaining stale tuples, exits the loop, and returnsNone(nullptrin C++). - Ties on
risk_score: Broken strictly by arrival counterseq, not alphabetically byunique_id. - Replacing a stored
unique_id: Updates score, payload, andseq(counting as a fresh arrival behind earlier equal-score detections) while invalidating the older heap entry. - Reusing a
unique_idafterGetNextserved it:del self.live_seq[unique_id]cleans up the ID on pop so a laterPuttreats it as a new arrival. - 64-bit
unsigned longboundaries (0to18,446,744,073,709,551,615): Handled cleanly by Python's unboundedintand 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_neededsweeps them out.
Common mistakes
- Calling
std::move(pq.top())onstd::priority_queuein C++:top()returns aconstreference so mutating it cannot break the heap invariant;std::moveon aconst Detection&silently copies theDetectionand itsdatastring. Usestd::vector+std::pop_heapand move fromheap_.back()before callingpop_back(), and wrap the moved value instd::unique_ptr(a C++ smart pointer expressing exclusive ownership of a heap-allocated object). - Negating
unsigned longin C++:-risk_scoreon an unsigned integer does modular wrap-around (-1ULbecomesULONG_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_seqinstead ofself.live_seq.get(unique_id) == seq: After an in-place replacement,unique_idis still inlive_seq, so failing to matchseqserves the outdated version! - Omitting
seqfrom the Python heap tuple: Writing(-risk_score, unique_id, data)breaks ties alphabetically byunique_id, and if two tuples share bothrisk_scoreandunique_id, Python comparesdata(or crashes withTypeErroron non-comparable payloads).
Alternative approaches
- Balanced binary search tree + hash index (
std::map+std::unordered_mapin C++): Store detections instd::map<Key, Detection>ordered by(risk_score DESC, seq ASC), paired withunordered_map<string, iterator>.Put,GetNext(begin()),Update, andRemoveall run in worst-caseO(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 contiguousstd::vectorheap. - Per-score FIFO buckets (
O(1)time): Ifrisk_scorecomes from a small bounded integer range such as0..100, an array of 101deques (plus a bitmask of non-empty buckets) supportsO(1)PutandO(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 astd::condition_variable(a synchronization primitive that puts waiting worker threads to sleep until notified).Putlocks the mutex, inserts the detection, unlocks, and callscv.notify_one().GetNext(timeout)acquires astd::unique_lockand callscv.wait_for(lock, timeout, predicate)where the predicate checkslive_seq_.size() > 0 || closed_— checkinglive_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 keepingunique_idrouting 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 deletesunique_idfromlive_seqinO(1)average time (and triggers_compact_if_neededif stale entries now dominate). To supportUpdate(unique_id, new_score)without the caller resupplyingdata, store the payload once inpayloads[unique_id] = dataand push lightweight(-new_score, seq, unique_id)entries into the heap inO(log n)amortized time. If worst-case (non-amortized)O(log n)time and zero stale entries are required, switch to C++17std::map<Key, Detection>+unordered_map<string, Key>, wheremap_.extract(old_key)re-keys the node inO(log n)without reallocating or copyingdata. - 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
nowasrisk_score + aging_rate * (now - arrival_time). Notice the algebraic trick when comparing two waiting itemsAandBat the samenow: addingaging_rate * nowshifts every waiting item equally and cancels out (score_A + rate * (now - t_A) > score_B + rate * (now - t_B)is identical toscore_A - rate * t_A > score_B - rate * t_B), so you can compute a fixed static priority keyscore - aging_rate * arrival_timeonce atPuttime 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 forrisk_score >= CRITICAL_THRESHOLDthat is always drained first, and an aged heap (or weighted fair share, such as serving 1 aged low-tier item everykpops) 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 untilGetNextfrees a slot, or (3) evict the lowest-priority stored detection if the incoming alert has higherrisk_score. Note that if replacement of an already-storedunique_idarrives while at capacity, it updates in place without increasing live countn. If policy (3) (evicting the minimum element) is chosen, a standard max-heap cannot find its minimum element in better thanO(n)time, so you should switch to a balanced tree (std::map), a min-max heap (a single array heap supporting bothO(log n)pop-max andO(log n)pop-min), or twin max/min heaps sharinglive_seqlazy deletion — and always emit metrics/audit logs whenever an alert is evicted or spilled.
Follow-up questions
- How would you synchronize concurrent producers and consumers, and support a timed blocking pop when the queue is empty?
- 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?
- If high-severity alerts arrive continuously, lower-severity ones could wait indefinitely—how can you prevent starvation while keeping critical alerts fast?
- How should the store behave if memory is capped at a fixed maximum capacity and a new alert arrives when full?
Similar questions
- TTL-Aware Key-Value Store and Networked Cache Architecture
- Conduct a Spoken Code Review of a Python Function with Tiered Severity
- Counting Orthogonal Land Regions in a Matrix
- Design an Asynchronous Multi-Engine File Malware Scanner
- Architecting and Defending a High-Security Event Streaming Backbone
- Distributed Worker Pool for High-Throughput Template Rendering
More Crowdstrike interview questions
- Architecting and Defending a High-Security Event Streaming Backbone Medium
- Distributed Worker Pool for High-Throughput Template Rendering Medium
- TTL-Aware Key-Value Store and Networked Cache Architecture Medium Pro
- Conduct a Spoken Code Review of a Python Function with Tiered Severity Medium Pro
- Counting Orthogonal Land Regions in a Matrix Medium Pro
- Design an Asynchronous Multi-Engine File Malware Scanner Medium Pro
- Highest Bottleneck Score in a Grid Medium Pro