Multi-Tier Weighted Cache With TTL Expiration
Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement an in-memory cache TieredExpiringStore that partitions weighted, time-limited entries across L ordered priority tiers (0 has the highest priority and L - 1 has the lowest). Tier i has total integer weight capacity capacities[i].
Support the class interface below together with the test harness function run_tiered_expiring_store:
class TieredExpiringStore:
def __init__(self, capacities: List[int]): ...
def put(self, item_id: str, weight: int, score: int, ttl: int, timestamp: int) -> bool: ...
def get(self, item_id: str, timestamp: int) -> Optional[int]: ...
def poll_highest(self, timestamp: int) -> Optional[Tuple[str, int]]: ...
def run_tiered_expiring_store(
capacities: List[int], operations: List[str], arguments: List[List]
) -> List:
Operational Rules
- TTL Expiration: An entry written at
timestampwith durationttlhasexpiry_time = timestamp + ttl. Whenever an operation runs at timetwitht >= expiry_time, that entry is expired: it is invisible to callers and itsweightis returned to its tier. - Insertion & Replacement (
put):- If
item_idis already live in any tier, delete the previous entry first and reclaim itsweightimmediately (even if the new entry turns out too heavy for every tier). - Inspect tiers in order
i = 0, 1, ..., L - 1, purging any expired entries in tieribefore testing headroom:- Upper tiers (
0 <= i < L - 1) must retain at least half of their capacity unused:used_weight + weight <= capacities[i] // 2. - The bottom tier (
i = L - 1, including Tier0whenL == 1) permits full utilization:used_weight + weight <= capacities[L - 1].
- Upper tiers (
- Place the entry into the earliest tier
ithat fits and returnTrue; if every tier overflows its limit, returnFalse.
- If
- Point Lookup (
get):- Return
scoreifitem_idis present andtimestamp < expiry_time; otherwise returnNone.
- Return
- Priority Eviction (
poll_highest):- Find the lowest tier index
i(0 <= i < L) holding at least one unexpired entry attimestamp. - Within tier
i, pick the live entry with the largestscore; break equal-score ties by the lexicographically smallestitem_id. - Delete that entry, reclaim its
weight, and return(item_id, score)(serialized as[item_id, score]byrun_tiered_expiring_store), orNoneif no live entries remain.
- Find the lowest tier index
Examples
Example 1
Input:
capacities = [80, 120]
operations = ["put", "put", "poll_highest", "get", "poll_highest"]
arguments = [["ord1", 30, 15, 8, 5], ["ord2", 25, 90, 12, 6], [10], ["ord2", 17], [18]]
Output:
[True, True, ["ord1", 15], 90, None]
Walk-through: Tier 0 caps usage at 80 // 2 = 40, whereas final Tier 1 allows 120. "ord1" (weight 30, expires at 13) lands in Tier 0; "ord2" (weight 25, expires at 18) would push Tier 0 to 55 > 40, so it spills into Tier 1. At t = 10, poll_highest drains Tier 0 first and returns ["ord1", 15] despite "ord2" having score 90. "ord2" is still live at t = 17 (90) and expires right at t = 18 (None).
Example 2
Input:
capacities = [20]
operations = ["put", "put", "put", "poll_highest"]
arguments = [["m2", 12, 40, 5, 1], ["m1", 8, 40, 15, 2], ["m3", 10, 40, 10, 6], [7]]
Output:
[True, True, True, ["m1", 40]]
Walk-through: With a single tier (L = 1), Tier 0 is the final tier and allows up to 20 weight, so "m2" (12) and "m1" (8) both fit (20 <= 20). At t = 6, "m2" expires (6 >= 6), freeing 12 units so "m3" (10) fits (8 + 10 = 18 <= 20). At t = 7, "m1" and "m3" tie at score 40, and "m1" < "m3" wins.
Constraints
1 <= len(capacities) <= 10and0 <= capacities[i] <= 10^9.weight >= 0,ttl >= 1,timestamp >= 0, andscoreis any signed integer.item_idis a non-empty ASCII string.- Operations should run in logarithmic amortized time per tier size via dual heaps and lazy deletion (
O(1)forget).
Step-by-step walkthrough
Understand the store rules and tier boundaries
We want to build
TieredExpiringStoreacrossLordered memory tiers (0is highest priority,L - 1is lowest priority). Every item has anitem_id, an integerweight, ascore, and an expiration timestampexpiry_time = timestamp + ttl.Three exact boundary rules govern every call:
- Half-open expiration (
timestamp >= expiry_time): An item inserted attimestamp = 10withttl = 3hasexpiry_time = 13. It is still alive at12, and expired at13(and every later time), freeing its weight. - 50% headroom on upper tiers, 100% on the last tier: When
putsearches tiers0throughL - 1for the first tier that fits:- Tiers
0 .. L - 2allowused_weight + weight <= capacities[i] // 2(preserving at least half the tier free). - The final tier
L - 1allowsused_weight + weight <= capacities[L - 1](even ifL == 1, Tier0is the final tier).
- Tiers
Example: capacities = [80, 120] Tier 0 (non-final): [#####.....] max usable = 80 // 2 = 40 (must keep >= 50% free) Tier 1 (final): [##########] max usable = 120 (can use up to 100%)- Tier-first priority in
poll_highest: Always choose from the lowest-numbered tier that still has a live item — even if a lower-priority tier holds an item with a much largerscore. Within that winning tier, pick the highestscore, breaking ties by the lexicographically smallestitem_id("a"before"b").
- Half-open expiration (
Why scanning a list is too slow, and how dual heaps fix it
A naive implementation stores all items in a plain list and scans it on every operation to drop expired items, sum each tier's weight, and find the best
(score, item_id). Each call takesO(N)time forNitems, which crawls whenNand the number of operations are both tens of thousands.Instead, we use Python's
heapq(binary min-heap: an array-backed tree whereheap[0]is always the smallest item, and pushing or popping takesO(log N)time) to maintain two heaps per tier alongside one master hash map:Master hash map (all live items across the store): items[item_id] -> (version, weight, score, expiry_time, tier) Per tier i (0 <= i < L): used_weight[i] -> integer sum of weights of live items in tier i expiry_heaps[i] -> min-heap of (expiry_time, version, item_id) [earliest expiry on top] score_heaps[i] -> min-heap of (-score, item_id, version) [highest score, smallest id on top]Notice the tuple field order in each heap: -
expiry_heaps[i]putsexpiry_timefirst so we can stop expiring items as soon asheap[0]hasexpiry_time > timestamp. -score_heaps[i]negatesscoreso Python's min-heap puts the largestscoreon top (even for negative scores:score = -5becomes5, beatingscore = -10which becomes10). Putting positiveitem_idsecond means equal scores break ties alphabetically ("a" < "b").Lazy deletion and why version numbers prevent ghost bugs
Every placed item sits inside two heaps (
expiry_heaps[tier]andscore_heaps[tier]). When an item is removed bypoll_highestor replaced byput, searching for its leftover tuple inside the middle of a binary heap would takeO(N)linear time.Instead, we use lazy deletion: removing an item only deletes it from
self.itemsand subtracts its weight fromself.used_weight[tier]inO(1)time. Its leftover tuples stay inside the heaps as harmless "ghosts" and are discarded later whenever they rise toheap[0].Why isn't checking
item_id in self.itemsenough to spot a ghost? Watch what happens if"A"is replaced with a longer TTL:t = 0: put("A", ttl=5) -> pushes (expiry=5, "A") to expiry_heap t = 1: put("A", ttl=100) -> replaces "A"; pushes (expiry=101, "A") to expiry_heap t = 5: old tuple (expiry=5, "A") reaches the top of expiry_heap! "A" IS in self.items — without a version tag, we would wrongly delete the NEW "A"!Giving every placement a monotonically increasing
version(0, 1, 2, ...) solves this completely: a heap tuple is valid if and only ifself.items.get(item_id)exists and has the exact sameversion.Code the store state and `O(1)` record helpers
Let's write
__init__along with_is_current,_place, and_remove:class TieredExpiringStore: def __init__(self, capacities: List[int]): self.capacities = list(capacities) num_tiers = len(self.capacities) # used_weight[tier]: integer sum of weights of currently live items in that tier, e.g. [30, 25] self.used_weight = [0] * num_tiers # expiry_heaps[tier]: min-heap of (expiry_time, version, item_id), e.g. [(13, 0, "ord1")]. # Earliest expiry_time sits on top; unique `version` comes second so item_ids never need comparison here. self.expiry_heaps: List[List[Tuple[int, int, str]]] = [] # score_heaps[tier]: min-heap of (-score, item_id, version), e.g. [(-15, "ord1", 0)]. # Negating score puts the highest score first (even for negative scores: -(-5) = 5 < 10 = -(-10)), # and placing positive item_id second breaks score ties lexicographically smallest first ("a" < "b"). self.score_heaps: List[List[Tuple[int, str, int]]] = [] for _ in range(num_tiers): self.expiry_heaps.append([]) self.score_heaps.append([]) # Master ledger of live items: item_id -> (version, weight, score, expiry_time, tier). self.items: Dict[str, Tuple[int, int, int, int, int]] = {} self.next_version = 0 def _is_current(self, item_id: str, version: int) -> bool: """Return True iff item_id is still live and matches this heap entry's version.""" record = self.items.get(item_id) if record is None: return False current_version = record[0] return current_version == version def _place(self, item_id: str, weight: int, score: int, expiry_time: int, tier: int) -> None: """Insert a fresh version of item_id into tier and push entries onto both tier heaps.""" version = self.next_version self.next_version += 1 self.items[item_id] = (version, weight, score, expiry_time, tier) self.used_weight[tier] += weight heapq.heappush(self.expiry_heaps[tier], (expiry_time, version, item_id)) heapq.heappush(self.score_heaps[tier], (-score, item_id, version)) def _remove(self, item_id: str) -> None: """Logically delete item_id in O(1) and reclaim its weight; heap entries are discarded lazily.""" version, weight, score, expiry_time, tier = self.items.pop(item_id) self.used_weight[tier] -= weightCode per-tier expiry cleanup and `O(1)` `get`
Before evaluating a candidate
tierinputorpoll_highest,_purge_tier(tier, timestamp)cleans out expired items from that tier'sexpiry_heap:- If the top entry is stale (
not _is_current), pop and discard it without touchingused_weight(its weight was already subtracted when it was removed). - Else if
expiry_time <= timestamp, pop it and call_remove(item_id)to reclaim its weight. - Else (
expiry_time > timestamp), stop immediately — every remaining live item in this tier expires even later!
For
get(item_id, timestamp), we do not even need to touch the heaps: we look upitem_iddirectly inself.itemsinO(1)time, and iftimestamp >= expiry_timewe call_remove(item_id)right away and returnNone:def _purge_tier(self, tier: int, timestamp: int) -> None: """Pop stale entries and expire items with expiry_time <= timestamp in a single tier.""" expiry_heap = self.expiry_heaps[tier] while expiry_heap: expiry_time, version, item_id = expiry_heap[0] if not self._is_current(item_id, version): # Already removed via put-replace, poll_highest, or get; drop stale heap node. heapq.heappop(expiry_heap) elif expiry_time <= timestamp: # Rule 1: expired when timestamp >= expiry_time; remove and reclaim weight. heapq.heappop(expiry_heap) self._remove(item_id) else: # Earliest remaining live item expires strictly after timestamp, so this tier is clean. break def get(self, item_id: str, timestamp: int) -> Optional[int]: record = self.items.get(item_id) if record is None: return None version, weight, score, expiry_time, tier = record # Rule 1: an item with timestamp >= expiry_time is expired; reclaim its weight immediately. if timestamp >= expiry_time: self._remove(item_id) return None return score- If the top entry is stale (
Code `put` and `poll_highest`
In
put, we first remove any existing record foritem_id. Doing this before scanning tiers reclaims its weight immediately (so an updated item can reuse its own freed space in Tier0), and also satisfies Rule 2 when the new weight is too big to fit anywhere. Then we check tiers0throughL - 1, purging each candidate tier right before testingused_weight[tier] + weight <= max_allowed_weight.In
poll_highest, we scan tiers0throughL - 1. For each tier,_purge_tierremoves any expired items first, so the very first current entry popped fromscore_heaps[tier]is guaranteed to be unexpired and optimal:def put(self, item_id: str, weight: int, score: int, ttl: int, timestamp: int) -> bool: # Rule 2: if item_id already exists anywhere, remove the old record first and reclaim its weight. if item_id in self.items: self._remove(item_id) last_tier = len(self.capacities) - 1 expiry_time = timestamp + ttl # Phase 1: Scan tiers from highest priority (0) to lowest priority (L - 1). for tier in range(len(self.capacities)): self._purge_tier(tier, timestamp) # Non-final tiers must keep >= 50% capacity free (used <= capacity // 2); final tier allows 100%. if tier < last_tier: max_allowed_weight = self.capacities[tier] // 2 else: max_allowed_weight = self.capacities[tier] # Phase 2: Place into the first tier whose capacity limit accommodates `weight`. if self.used_weight[tier] + weight <= max_allowed_weight: self._place(item_id, weight, score, expiry_time, tier) return True return False def poll_highest(self, timestamp: int) -> Optional[Tuple[str, int]]: # Rule 3: inspect tiers from 0 to L - 1 and pick from the first tier with a live item. for tier in range(len(self.capacities)): self._purge_tier(tier, timestamp) score_heap = self.score_heaps[tier] while score_heap: neg_score, item_id, version = heapq.heappop(score_heap) if self._is_current(item_id, version): # Because _purge_tier just ran, any current item in this tier is guaranteed unexpired. self._remove(item_id) return (item_id, -neg_score) return NoneTrace Example 1 step by step
Let's trace Example 1 with
capacities = [80, 120](Tier 0 limit =40, Tier 1 limit =120):1. put("ord1", weight=30, score=15, ttl=8, timestamp=5): expiry = 13. Tier 0: 0 + 30 <= 40 -> fits! items = {"ord1": (v=0, w=30, s=15, exp=13, tier=0)}, used_weight = [30, 0] -> True 2. put("ord2", weight=25, score=90, ttl=12, timestamp=6): expiry = 18. Tier 0: 30 + 25 = 55 > 40 (spills!). Tier 1: 0 + 25 <= 120 -> fits! items = {"ord1": (v=0, ...), "ord2": (v=1, w=25, s=90, exp=18, tier=1)}, used_weight = [30, 25] -> True 3. poll_highest(timestamp=10): Tier 0: _purge_tier(0, 10) keeps "ord1" (13 > 10). score_heaps[0] pops (-15, "ord1", v=0) -> current! Remove "ord1", used_weight = [0, 25]. Returns ["ord1", 15] (Tier 0 beats Tier 1 even though "ord2" has higher score 90). 4. get("ord2", timestamp=17): "ord2" is in items with expiry = 18 > 17 -> still live! Returns 90. 5. poll_highest(timestamp=18): Tier 0 heaps hold stale (13, v=0, "ord1") -> dropped. Tier 1 _purge_tier(1, 18) sees (18, v=1, "ord2") with 18 <= 18 -> expired! _remove("ord2"), used_weight = [0, 0]. score_heaps[1] pops stale (-90, "ord2", v=1) -> dropped. Returns None.Complete solution
Adding the
run_tiered_expiring_storejudge harness wrapper (converting polled(item_id, score)tuples into[item_id, score]lists) completes the solution:from typing import Any, Dict, List, Optional, Set, Tuple import heapq class TieredExpiringStore: def __init__(self, capacities: List[int]): self.capacities = list(capacities) num_tiers = len(self.capacities) # used_weight[tier]: integer sum of weights of currently live items in that tier, e.g. [30, 25] self.used_weight = [0] * num_tiers # expiry_heaps[tier]: min-heap of (expiry_time, version, item_id), e.g. [(13, 0, "ord1")]. # Earliest expiry_time sits on top; unique `version` comes second so item_ids never need comparison here. self.expiry_heaps: List[List[Tuple[int, int, str]]] = [] # score_heaps[tier]: min-heap of (-score, item_id, version), e.g. [(-15, "ord1", 0)]. # Negating score puts the highest score first (even for negative scores: -(-5) = 5 < 10 = -(-10)), # and placing positive item_id second breaks score ties lexicographically smallest first ("a" < "b"). self.score_heaps: List[List[Tuple[int, str, int]]] = [] for _ in range(num_tiers): self.expiry_heaps.append([]) self.score_heaps.append([]) # Master ledger of live items: item_id -> (version, weight, score, expiry_time, tier). self.items: Dict[str, Tuple[int, int, int, int, int]] = {} self.next_version = 0 def _is_current(self, item_id: str, version: int) -> bool: """Return True iff item_id is still live and matches this heap entry's version.""" record = self.items.get(item_id) if record is None: return False current_version = record[0] return current_version == version def _place(self, item_id: str, weight: int, score: int, expiry_time: int, tier: int) -> None: """Insert a fresh version of item_id into tier and push entries onto both tier heaps.""" version = self.next_version self.next_version += 1 self.items[item_id] = (version, weight, score, expiry_time, tier) self.used_weight[tier] += weight heapq.heappush(self.expiry_heaps[tier], (expiry_time, version, item_id)) heapq.heappush(self.score_heaps[tier], (-score, item_id, version)) def _remove(self, item_id: str) -> None: """Logically delete item_id in O(1) and reclaim its weight; heap entries are discarded lazily.""" version, weight, score, expiry_time, tier = self.items.pop(item_id) self.used_weight[tier] -= weight def _purge_tier(self, tier: int, timestamp: int) -> None: """Pop stale entries and expire items with expiry_time <= timestamp in a single tier.""" expiry_heap = self.expiry_heaps[tier] while expiry_heap: expiry_time, version, item_id = expiry_heap[0] if not self._is_current(item_id, version): # Already removed via put-replace, poll_highest, or get; drop stale heap node. heapq.heappop(expiry_heap) elif expiry_time <= timestamp: # Rule 1: expired when timestamp >= expiry_time; remove and reclaim weight. heapq.heappop(expiry_heap) self._remove(item_id) else: # Earliest remaining live item expires strictly after timestamp, so this tier is clean. break def put(self, item_id: str, weight: int, score: int, ttl: int, timestamp: int) -> bool: # Rule 2: if item_id already exists anywhere, remove the old record first and reclaim its weight. if item_id in self.items: self._remove(item_id) last_tier = len(self.capacities) - 1 expiry_time = timestamp + ttl # Phase 1: Scan tiers from highest priority (0) to lowest priority (L - 1). for tier in range(len(self.capacities)): self._purge_tier(tier, timestamp) # Non-final tiers must keep >= 50% capacity free (used <= capacity // 2); final tier allows 100%. if tier < last_tier: max_allowed_weight = self.capacities[tier] // 2 else: max_allowed_weight = self.capacities[tier] # Phase 2: Place into the first tier whose capacity limit accommodates `weight`. if self.used_weight[tier] + weight <= max_allowed_weight: self._place(item_id, weight, score, expiry_time, tier) return True return False def get(self, item_id: str, timestamp: int) -> Optional[int]: record = self.items.get(item_id) if record is None: return None version, weight, score, expiry_time, tier = record # Rule 1: an item with timestamp >= expiry_time is expired; reclaim its weight immediately. if timestamp >= expiry_time: self._remove(item_id) return None return score def poll_highest(self, timestamp: int) -> Optional[Tuple[str, int]]: # Rule 3: inspect tiers from 0 to L - 1 and pick from the first tier with a live item. for tier in range(len(self.capacities)): self._purge_tier(tier, timestamp) score_heap = self.score_heaps[tier] while score_heap: neg_score, item_id, version = heapq.heappop(score_heap) if self._is_current(item_id, version): # Because _purge_tier just ran, any current item in this tier is guaranteed unexpired. self._remove(item_id) return (item_id, -neg_score) return None def run_tiered_expiring_store(capacities: List[int], operations: List[str], arguments: List[List]) -> List: store = TieredExpiringStore(capacities) results = [] for op, args in zip(operations, arguments): if op == "put": item_id, weight, score, ttl, timestamp = args results.append(store.put(item_id, weight, score, ttl, timestamp)) elif op == "get": item_id, timestamp = args results.append(store.get(item_id, timestamp)) elif op == "poll_highest": timestamp = args[0] polled = store.poll_highest(timestamp) if polled is None: results.append(None) else: # Convert (item_id, score) tuple to a two-element list to match expected judge output. polled_id, polled_score = polled results.append([polled_id, polled_score]) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine managing a multi-shelf pharmacy cabinet where Shelf 0 is the eye-level shelf (kept at least 50% empty so high-priority items have room) and the bottom shelf can pack to 100%. Every bottle has a priority score and a TTL (time-to-live) — the duration it stays valid before expiring. Instead of rummaging through every bottle on a shelf to find expired items and rummaging again to pick the highest-scored bottle, we combine three simple structures:
- One master inventory ledger (
self.items): a hash map storing only currently live items along with their weight, tier, expiry time, and a uniqueversionnumber. - Two sorted clipboards per shelf: two min-heaps (array-backed trees that keep the smallest tuple on top and support push/pop in
O(log N)time) —expiry_heaps[i]ordered by earliest expiration time, andscore_heaps[i]ordered by(-score, item_id, version)so the highest score and lexicographically (dictionary / ASCII order) smallest ID sit on top. - Lazy deletion: when an item is removed or overwritten, we delete it from
self.itemsand subtract itsweightinO(1)time, leaving its old heap entries behind until they reach the top of a heap and fail theversioncheck.
Why does the naive approach fall short? Keeping items in a plain list requires scanning all N stored items on every put, get, and poll_highest to purge expired items, recompute tier weights, and find the highest score, costing O(N) per call (10^10 steps for 10^5 items and 10^5 operations). Even with heaps, eagerly deleting an item from the middle of the other heap still requires an O(N) search unless you use lazy deletion or custom index-tracking heaps.
Let's trace Example 1 with capacities = [80, 120] (Tier 0 usable limit 80 // 2 = 40, Tier 1 usable limit 120):
1. put("ord1", weight=30, score=15, ttl=8, timestamp=5): expires at 13; 0 + 30 <= 40, so "ord1" goes into Tier 0 with version = 0.
2. put("ord2", weight=25, score=90, ttl=12, timestamp=6): expires at 18; Tier 0 would reach 30 + 25 = 55 > 40, so "ord2" spills into Tier 1 with version = 1.
3. poll_highest(10): Tier 0 is checked first, "ord1" is unexpired (13 > 10), so ("ord1", 15) is popped and removed from items — beating "ord2"'s score of 90 because Tier 0 has higher tier priority.
4. get("ord2", 17) and poll_highest(18): "ord2" is still valid at 17 < 18 (returning 90), then expires right at 18 >= 18, where _purge_tier reclaims its weight and poll_highest returns None.
Complexity
Let L be the number of tiers and P be the total number of put operations so far.
- Time:
get: O(1) worst-case, because we perform one hash-map lookup inself.itemsand, if the item is expired, oneO(1)removal fromself.itemsandself.used_weight.putandpoll_highest: O(L + log P) amortized per call (amortized means averaged per operation across the whole sequence, even if an occasional call pops several expired entries at once). Eachputchecks at mostLtiers and pushes two heap tuples inO(log P)time; every pushed tuple is popped at most once across the entire run during_purge_tierorpoll_highest, so total heap pop work over all calls never exceedsO(P log P).
- Space: O(L + P), because
self.itemsstores at most the currently live items while the2 * Lheaps hold at most2 * Plive and stale tuples combined. (If memory must stay strictly proportional to live itemsNduring long-running workloads with heavy overwrites, rebuild a tier's two heaps fromself.itemsinO(N_tier)time whenever stale tuples in that tier exceed2 * N_tier.)
Edge cases
- Exact 50% capacity boundary: In a non-final tier of capacity
100,used_weight + weight == 50succeeds (<=), whereas51spills to the next tier. - Odd tier capacities: Integer floor division (
7 // 2 = 3) ensures at least 50% of capacity (4out of7) stays free; capacities of0or1on non-final tiers only accept weight-0items. - Single-tier store (
L = 1): Tier0is the final tierL - 1, so it uses 100% capacity rather than 50% (tested in Example 2). - Exact expiration timestamp (
timestamp == expiry_time): Considered expired (timestamp >= expiry_time), so the item is invisible toget/poll_highestand its weight is immediately reusable byput. - Replacing an existing
item_id: The old record is removed before checking tier capacities, allowing the replacement to fit into the same (or higher) tier using reclaimed weight; if the new weight fits nowhere,putreturnsFalseand the old record stays removed. - Replacing with a later expiration: Because
versionincrements on every_place, the old record's earlier expiration tuple fails_is_currentand cannot prematurely delete the newly placed item. - Negative and tied scores in
poll_highest:(-score, item_id, version)orders-5(5) ahead of-10(10) and comparesitem_idin ascending order when-scoreis equal, deterministically picking"a"before"b".
Common mistakes
- Using
<instead of<=on capacity limits: Rejects valid placements that land squarely oncapacities[i] // 2orcapacities[L - 1]. - Applying the 50% cap to the last tier (
L - 1): Fails wheneverL == 1or when the final fallback tier needs its full capacity. - Using
timestamp > expiry_timeinstead oftimestamp >= expiry_time: Keeps items alive for one extra tick past their TTL. - Lazy deletion without a
versionnumber: Checkingitem_id in self.itemsalone mistakes stale heap entries of a replaceditem_idfor the new live record, corrupting both expiration andpoll_highestscores. - Putting
versionbeforeitem_idinscore_heaps: Writing(-score, version, item_id)breaks score ties by insertion order instead of lexicographically smallestitem_id. - Picking the highest score globally instead of tier-first:
poll_highestmust drain every valid item from Tier0before ever considering Tier1. - Removing the old record after checking capacity on a
putreplacement: Double-counts the item's old and new weights during placement, forcing unnecessary spills to lower tiers.
Alternative approaches
- Balanced binary search trees per tier (
O(log N_tier)worst-case,O(N)live space): Using two balanced binary search trees (self-balancing sorted trees that support lookup, insert, and delete in logarithmic time) per tier — one ordered by(expiry_time, item_id)and one by(-score, item_id)— lets_removeerase both entries eagerly inO(log N_tier)time with zero stale entries and noversioncounter. Python's standard library does not include a balanced tree, making dualheapqheaps with versioned lazy deletion the standard interview choice. - Flat list scan (
O(N)per call): Easy to write in 40 lines and invaluable as a brute-force reference in randomized tests, but too slow for largeN.
Follow-up questions
- How can you make the store safe for concurrent readers and writers while avoiding a single global lock bottleneck? Starting with a single coarse mutex — a lock that lets only one thread access the store at a time — is simple and bug-free at moderate request rates, but serializes all readers and writers. To reduce contention, store
itemsin a sharded concurrent hash map sogetreads without locking tier heaps (performing an atomic compare-and-remove only if it encounters an expired record), and give each tier its own lock always acquired in strictly ascending order (0, 1, ..., L - 1) so two concurrent writers can never deadlock (freeze while waiting on each other's locks). In ultra-low-latency systems, an even faster design dedicates a single-threaded event loop to own the store, fed by lock-free ring buffers (fixed-size circular queues in shared memory that pass messages between threads without locks). - Suppose freeing capacity in an upper tier should automatically pull eligible items up from lower tiers. How would you keep updates logarithmic? Whenever weight is reclaimed in tier
i(via expiry,poll_highest, or replacement), we want to pull eligible items up from tieri + 1. If the policy promotes the highest-priority item only if it fits, peeking atscore_heaps[i + 1]works inO(log N); if the policy promotes the highest-scoring item among those whose weight fits the available headroom, replacescore_heaps[i + 1]with an augmented balanced binary search tree keyed by(-score, item_id)where each tree node caches the minimumweightin its subtree, letting you locate the highest-priority fitting candidate inO(log N)time (while capping promotions per call to prevent cascading moves across many tiers). - What happens if multiple callers pass out-of-order timestamps due to network jitter or clock drift, and how would you address it? Clock skew — small disagreements between different machines' clocks — means an earlier-timestamped event can arrive after a later timestamp has already purged expired items, making results depend on network arrival order. The cleanest fix in an in-memory store is server-assigned ingestion timestamps from a single monotonic clock on the store host (or clamping
effective_ts = max(timestamp, max_seen_ts)). If producer event timestamps must be honored strictly, buffer incoming requests briefly in a min-heap ordered by event timestamp and execute them in order up to a watermark — a lower-bound timestamp guaranteeing no older events will be accepted — while routing late arrivals past the watermark to a fallback or rejection path.
Follow-up questions
- How can you make the store safe for concurrent readers and writers while avoiding a single global lock bottleneck?
- Suppose freeing capacity in an upper tier should automatically pull eligible items up from lower tiers. How would you keep updates logarithmic?
- What happens if multiple callers pass out-of-order timestamps due to network jitter or clock drift, and how would you address it?
Similar questions
- Selecting Python, Java, or C++ Across Trading Services
- Hexadecimal String Bitwise AND
- Maximum Node Value in an Unordered Binary Tree
- Controlled Month-Range Selectors in React
- February 2024 Application Resource Averages
- SQL Semantics Multiple-Choice Reasoning
More Akuna Capital interview questions
- Limit Order Book Matching Engine Hard
- Single-Channel Two-Party Call Manager With Custom Exceptions Medium
- Hexadecimal String Bitwise AND Medium Pro
- Maximum Node Value in an Unordered Binary Tree Medium Pro
- Single-Channel Two-Party Call Controller Medium Pro
- SQL Semantics Multiple-Choice Reasoning Medium Pro
- Selecting Python, Java, or C++ Across Trading Services Hard Pro
- Net Portfolio Deltas by Asset Group Medium Pro
- Optimal Multi-Symbol Trading Plan Medium Pro
- Fewest Operations to Reach Target Integer Medium Pro