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

  1. TTL Expiration: An entry written at timestamp with duration ttl has expiry_time = timestamp + ttl. Whenever an operation runs at time t with t >= expiry_time, that entry is expired: it is invisible to callers and its weight is returned to its tier.
  2. Insertion & Replacement (put):
    • If item_id is already live in any tier, delete the previous entry first and reclaim its weight immediately (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 tier i before 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 Tier 0 when L == 1) permits full utilization: used_weight + weight <= capacities[L - 1].
    • Place the entry into the earliest tier i that fits and return True; if every tier overflows its limit, return False.
  3. Point Lookup (get):
    • Return score if item_id is present and timestamp < expiry_time; otherwise return None.
  4. Priority Eviction (poll_highest):
    • Find the lowest tier index i (0 <= i < L) holding at least one unexpired entry at timestamp.
    • Within tier i, pick the live entry with the largest score; break equal-score ties by the lexicographically smallest item_id.
    • Delete that entry, reclaim its weight, and return (item_id, score) (serialized as [item_id, score] by run_tiered_expiring_store), or None if no live entries remain.

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) <= 10 and 0 <= capacities[i] <= 10^9.
  • weight >= 0, ttl >= 1, timestamp >= 0, and score is any signed integer.
  • item_id is a non-empty ASCII string.
  • Operations should run in logarithmic amortized time per tier size via dual heaps and lazy deletion (O(1) for get).

Step-by-step walkthrough

  1. Understand the store rules and tier boundaries

    We want to build TieredExpiringStore across L ordered memory tiers (0 is highest priority, L - 1 is lowest priority). Every item has an item_id, an integer weight, a score, and an expiration timestamp expiry_time = timestamp + ttl.

    Three exact boundary rules govern every call:

    1. Half-open expiration (timestamp >= expiry_time): An item inserted at timestamp = 10 with ttl = 3 has expiry_time = 13. It is still alive at 12, and expired at 13 (and every later time), freeing its weight.
    2. 50% headroom on upper tiers, 100% on the last tier: When put searches tiers 0 through L - 1 for the first tier that fits:
      • Tiers 0 .. L - 2 allow used_weight + weight <= capacities[i] // 2 (preserving at least half the tier free).
      • The final tier L - 1 allows used_weight + weight <= capacities[L - 1] (even if L == 1, Tier 0 is the final tier).
    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%)
    
    1. 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 larger score. Within that winning tier, pick the highest score, breaking ties by the lexicographically smallest item_id ("a" before "b").
  2. 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 takes O(N) time for N items, which crawls when N and the number of operations are both tens of thousands.

    Instead, we use Python's heapq (binary min-heap: an array-backed tree where heap[0] is always the smallest item, and pushing or popping takes O(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] puts expiry_time first so we can stop expiring items as soon as heap[0] has expiry_time > timestamp. - score_heaps[i] negates score so Python's min-heap puts the largest score on top (even for negative scores: score = -5 becomes 5, beating score = -10 which becomes 10). Putting positive item_id second means equal scores break ties alphabetically ("a" < "b").

  3. Lazy deletion and why version numbers prevent ghost bugs

    Every placed item sits inside two heaps (expiry_heaps[tier] and score_heaps[tier]). When an item is removed by poll_highest or replaced by put, searching for its leftover tuple inside the middle of a binary heap would take O(N) linear time.

    Instead, we use lazy deletion: removing an item only deletes it from self.items and subtracts its weight from self.used_weight[tier] in O(1) time. Its leftover tuples stay inside the heaps as harmless "ghosts" and are discarded later whenever they rise to heap[0].

    Why isn't checking item_id in self.items enough 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 if self.items.get(item_id) exists and has the exact same version.

  4. 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] -= weight
    
  5. Code per-tier expiry cleanup and `O(1)` `get`

    Before evaluating a candidate tier in put or poll_highest, _purge_tier(tier, timestamp) cleans out expired items from that tier's expiry_heap:

    • If the top entry is stale (not _is_current), pop and discard it without touching used_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 up item_id directly in self.items in O(1) time, and if timestamp >= expiry_time we call _remove(item_id) right away and return None:

        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
    
  6. Code `put` and `poll_highest`

    In put, we first remove any existing record for item_id. Doing this before scanning tiers reclaims its weight immediately (so an updated item can reuse its own freed space in Tier 0), and also satisfies Rule 2 when the new weight is too big to fit anywhere. Then we check tiers 0 through L - 1, purging each candidate tier right before testing used_weight[tier] + weight <= max_allowed_weight.

    In poll_highest, we scan tiers 0 through L - 1. For each tier, _purge_tier removes any expired items first, so the very first current entry popped from score_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 None
    
  7. Trace 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.
    
  8. Complete solution

    Adding the run_tiered_expiring_store judge 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 unique version number.
  • 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, and score_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.items and subtract its weight in O(1) time, leaving its old heap entries behind until they reach the top of a heap and fail the version check.

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 in self.items and, if the item is expired, one O(1) removal from self.items and self.used_weight.
    • put and poll_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). Each put checks at most L tiers and pushes two heap tuples in O(log P) time; every pushed tuple is popped at most once across the entire run during _purge_tier or poll_highest, so total heap pop work over all calls never exceeds O(P log P).
  • Space: O(L + P), because self.items stores at most the currently live items while the 2 * L heaps hold at most 2 * P live and stale tuples combined. (If memory must stay strictly proportional to live items N during long-running workloads with heavy overwrites, rebuild a tier's two heaps from self.items in O(N_tier) time whenever stale tuples in that tier exceed 2 * N_tier.)

Edge cases

  • Exact 50% capacity boundary: In a non-final tier of capacity 100, used_weight + weight == 50 succeeds (<=), whereas 51 spills to the next tier.
  • Odd tier capacities: Integer floor division (7 // 2 = 3) ensures at least 50% of capacity (4 out of 7) stays free; capacities of 0 or 1 on non-final tiers only accept weight-0 items.
  • Single-tier store (L = 1): Tier 0 is the final tier L - 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 to get/poll_highest and its weight is immediately reusable by put.
  • 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, put returns False and the old record stays removed.
  • Replacing with a later expiration: Because version increments on every _place, the old record's earlier expiration tuple fails _is_current and 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 compares item_id in ascending order when -score is equal, deterministically picking "a" before "b".

Common mistakes

  • Using < instead of <= on capacity limits: Rejects valid placements that land squarely on capacities[i] // 2 or capacities[L - 1].
  • Applying the 50% cap to the last tier (L - 1): Fails whenever L == 1 or when the final fallback tier needs its full capacity.
  • Using timestamp > expiry_time instead of timestamp >= expiry_time: Keeps items alive for one extra tick past their TTL.
  • Lazy deletion without a version number: Checking item_id in self.items alone mistakes stale heap entries of a replaced item_id for the new live record, corrupting both expiration and poll_highest scores.
  • Putting version before item_id in score_heaps: Writing (-score, version, item_id) breaks score ties by insertion order instead of lexicographically smallest item_id.
  • Picking the highest score globally instead of tier-first: poll_highest must drain every valid item from Tier 0 before ever considering Tier 1.
  • Removing the old record after checking capacity on a put replacement: 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 _remove erase both entries eagerly in O(log N_tier) time with zero stale entries and no version counter. Python's standard library does not include a balanced tree, making dual heapq heaps 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 large N.

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 items in a sharded concurrent hash map so get reads 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 tier i + 1. If the policy promotes the highest-priority item only if it fits, peeking at score_heaps[i + 1] works in O(log N); if the policy promotes the highest-scoring item among those whose weight fits the available headroom, replace score_heaps[i + 1] with an augmented balanced binary search tree keyed by (-score, item_id) where each tree node caches the minimum weight in its subtree, letting you locate the highest-priority fitting candidate in O(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

Similar questions

More Akuna Capital interview questions

All 26 Akuna Capital questions →