Point-in-Time Credit Ledger with Expiring Grants
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement an in-memory credit accounting ledger where credits are issued as time-bounded grants, usage is deducted against active grants, events may be logged out of chronological order, and callers query the remaining balance at any integer timestamp.
Operations & Semantics
-
Part 1 —
CreditLedger:add_credit(grant_id: str, amount: int, timestamp: int, expiration: int) -> None: Registers a credit grant identified bygrant_idholdingamountcredits, active on the half-open windowtimestamp <= t < expiration(usable starting attimestamp, expired atexpiration).subtract(amount: int, timestamp: int) -> None: Logs a deduction ofamountcredits occurring attimestamp.get_balance(timestamp: int) -> int: Computes the total unused, unexpired credit available attimestampafter applying every logged event with event time<= timestampin chronological order, regardless of arrival order.
-
Ordering, Tie-Breaking, Overdraft, and Validation Rules:
- Same-timestamp ordering: When grants and deductions share the exact same timestamp
t, all grants starting atttake effect before any deduction att. Multiple deductions attapply in arrival order. - Earliest-expiration-first consumption: A deduction at time
tdraws from currently active grants (start <= t < expiration) ordered by smallestexpirationfirst. Ties inexpirationare broken by lexicographically smallestgrant_id. - Capped overdraft (no debt): If a deduction at time
texceeds total active credits att, every active grant is drained to0and the uncovered remainder is discarded — balances never go negative and future grants are unaffected. - Validation:
add_creditraisesValueErrorifgrant_idwas already used,amount <= 0, orexpiration <= timestamp(leaving ledger state untouched on error).subtractraisesValueErrorifamount <= 0.
- Same-timestamp ordering: When grants and deductions share the exact same timestamp
-
Part 2 —
CheckpointedCreditLedger(interval: int = 64):- Exposes the exact same methods and results as
CreditLedger(raisingValueErrorifinterval < 1), but stores periodic state checkpoints everyintervalevents soget_balanceresumes from the nearest valid checkpoint rather than replaying from event0, discarding only checkpoints invalidated when an out-of-order event inserts earlier in the timeline.
- Exposes the exact same methods and results as
class CreditLedger:
def __init__(self) -> None: ...
def add_credit(self, grant_id: str, amount: int, timestamp: int, expiration: int) -> None: ...
def subtract(self, amount: int, timestamp: int) -> None: ...
def get_balance(self, timestamp: int) -> int: ...
class CheckpointedCreditLedger:
def __init__(self, interval: int = 64) -> None: ...
def add_credit(self, grant_id: str, amount: int, timestamp: int, expiration: int) -> None: ...
def subtract(self, amount: int, timestamp: int) -> None: ...
def get_balance(self, timestamp: int) -> int: ...
Examples
Example 1
ledger = CreditLedger()
ledger.add_credit("base", 80, 0, 60)
ledger.add_credit("promo", 50, 5, 25)
ledger.subtract(65, 15)
ledger.get_balance(15) -> 65
ledger.get_balance(30) -> 65
ledger.subtract(30, 10) # out-of-order deduction logged later
ledger.get_balance(12) -> 100
ledger.get_balance(30) -> 35
ledger.get_balance(60) -> 0
Before the late event arrives, subtract(65, 15) drains all 50 credits from "promo" (which expires at 25 < 60) plus 15 from "base", leaving 65 in "base" at both t = 15 and t = 30. Once subtract(30, 10) arrives, chronological replay spends 30 from "promo" at t = 10 (leaving 20 + 80 = 100 at t = 12), so subtract(65, 15) can only pull 20 from "promo" and must pull 45 from "base", lowering the balance at t = 30 to 35.
Example 2
ledger = CheckpointedCreditLedger(interval=2)
ledger.add_credit("g2", 40, 10, 40)
ledger.add_credit("g1", 25, 10, 40)
ledger.subtract(30, 10)
ledger.get_balance(10) -> 35
ledger.subtract(50, 20)
ledger.add_credit("g3", 15, 25, 50)
ledger.get_balance(20) -> 0
ledger.get_balance(30) -> 15
At t = 10, both grants activate before subtract(30, 10) and tie on expiration = 40; "g1" < "g2" drains "g1" (25) plus 5 from "g2", leaving 35. At t = 20, subtract(50, 20) drains "g2" to 0 and drops the extra 15, so "g3" keeps all 15 credits at t = 30.
Constraints
timestampandexpirationare integers withtimestamp < expirationfor valid grants.amount >= 1for validadd_creditandsubtractcalls.grant_idis a unique string across all successfuladd_creditcalls on a ledger instance.interval >= 1forCheckpointedCreditLedger.
Step-by-step walkthrough
Pin down every boundary rule before coding
Before writing code, let us verify all boundary rules so replaying the same set of events is 100% deterministic:
- Half-open validity interval (
timestamp <= t < expiration): A grant becomes usable attimestamp(inclusive) and expires atexpiration(exclusive). Att == expiration, its remaining credits are already expired. - Same-timestamp ordering: Grants starting at
ttake effect before deductions att, allowing a grant that activates attto fund a deduction att. Multiple deductions attapply in the order they were logged. - Equal-expiration tie-breaker: When two active grants expire at the same timestamp, consume from the smaller
grant_idfirst ("g1" < "g2"). - Capped overdraft: When a deduction requests more credits than all currently active grants hold, drain active grants to
0and discard the uncovered excess — never carry negative balances or future debt. Notice whysubtractcannot raise on insufficient funds when logged: a grant covering that timestamp might arrive later out of order. - Input validation: Raise
ValueErrorfor duplicategrant_id,amount <= 0,expiration <= timestamp, orinterval < 1.
- Half-open validity interval (
Keep events sorted in chronological replay order
Because
add_creditandsubtractcalls can arrive out of timestamp order, updating a single live integer balance fails whenever an earlier event arrives late. Instead, keep all logged events sorted in exact chronological replay order insideself.events.Packing each event into a 6-tuple whose fields appear in priority order lets Python's natural tuple comparison order events automatically:
event tuple: (timestamp, kind, seq, amount, grant_id, expiration) | | GRANT = 0 -------+ +--> 0, 1, 2, ... arrival counter SUBTRACT = 1 (breaks ties so None fields are never compared)When
get_balance(t)executes, every event with timestamp<= tforms a contiguous prefixself.events[:event_count]. We locateevent_countinO(log N)time viabisect.bisect_rightwith the 2-tuple probe(t, SUBTRACT + 1):events: (5, 0, ...) (10, 0, ...) (10, 1, ...) | (15, 1, ...) ^ probe = (10, 2) lands here -> event_count = 3Because every real event at timestamp
10haskindequal to0or1(< 2), and every event at11+has a larger index-0 timestamp, Python stops comparing at index1and returns the exact prefix count.from typing import List import bisect import heapq GRANT = 0 SUBTRACT = 1 class CreditLedger: def __init__(self) -> None: # events: sorted list of (timestamp, kind, seq, amount, grant_id, expiration) tuples self.events: List[tuple] = [] self.grant_ids = set() self.next_seq = 0 def _record(self, event: tuple) -> int: """Insert `event` into `self.events` in sorted replay order and return its index.""" insert_pos = bisect.bisect_right(self.events, event) self.events.insert(insert_pos, event) return insert_pos def _count_events_up_to(self, timestamp: int) -> int: """Return how many recorded events have event_timestamp <= `timestamp`.""" probe = (timestamp, SUBTRACT + 1) return bisect.bisect_right(self.events, probe)Drain earliest-expiring grants with a min-heap
During replay, each deduction needs quick access to whichever active grant expires soonest. A min-heap (a binary-heap array whose smallest item always sits at index
0withO(log H)push/pop) provides that directly.Represent each heap entry as a 3-element list
[expiration, grant_id, remaining]:- Why a mutable
list? Partial deductions decrementremainingin place (earliest_grant[2] -= used). Becausegrant_idis unique, two entries never tie on(expiration, grant_id), soheapqnever compares index2and in-place decrements preserve the heap invariant. - Lazy eviction of expired grants: When processing a deduction at
timestamp, ifgrants[0]hasexpiration <= timestamp, it is already expired. Because replay advances monotonically in timestamp order, that grant remains expired for all subsequent events too, so popping it permanently is safe. - Final unexpired sum: Grants that expire after the last deduction remain in the heap when replay stops, so
sum_unexpiredfilters entries withexpiration > query_time.
def apply_event(grants: List[list], event: tuple) -> None: """Apply a single sorted event to the active grant min-heap.""" timestamp, kind, _seq, amount, grant_id, expiration = event if kind == GRANT: heapq.heappush(grants, [expiration, grant_id, amount]) return needed = amount while needed > 0 and grants: earliest_grant = grants[0] grant_expiration = earliest_grant[0] if grant_expiration <= timestamp: heapq.heappop(grants) continue available_in_grant = earliest_grant[2] used = min(needed, available_in_grant) earliest_grant[2] -= used needed -= used if earliest_grant[2] == 0: heapq.heappop(grants) def sum_unexpired(grants: List[list], query_time: int) -> int: """Return total remaining credits among grants in `grants` that have not expired at `query_time`.""" total = 0 for expiration, _grant_id, remaining in grants: if expiration > query_time: total += remaining return total- Why a mutable
Complete Part 1 and trace Example 1
Validate all arguments in
add_creditbefore mutatingself.grant_idsso rejected calls leave no side effects:def add_credit(self, grant_id: str, amount: int, timestamp: int, expiration: int) -> None: if grant_id in self.grant_ids: raise ValueError(f"duplicate grant id {grant_id!r}") if amount <= 0: raise ValueError("amount must be positive") if expiration <= timestamp: raise ValueError("a grant must expire after it starts") self.grant_ids.add(grant_id) seq = self.next_seq self.next_seq += 1 event = (timestamp, GRANT, seq, amount, grant_id, expiration) self._record(event) def subtract(self, amount: int, timestamp: int) -> None: if amount <= 0: raise ValueError("amount must be positive") seq = self.next_seq self.next_seq += 1 event = (timestamp, SUBTRACT, seq, amount, None, None) self._record(event) def get_balance(self, timestamp: int) -> int: event_count = self._count_events_up_to(timestamp) grants: List[list] = [] for idx in range(event_count): apply_event(grants, self.events[idx]) return sum_unexpired(grants, timestamp)Trace Example 1 to see how out-of-order replay adjusts downstream balances:
Initial events: "base" (80, [0, 60)), "promo" (50, [5, 25)), subtract(65, t=15) Sorted prefix up to t=30: 1. t=0 grant "base": heap = [[60, "base", 80]] 2. t=5 grant "promo": heap = [[25, "promo", 50], [60, "base", 80]] 3. t=15 sub 65: takes 50 from "promo" (popped) + 15 from "base" -> [[60, "base", 65]] sum_unexpired(t=30): 60 > 30 -> 65 Late arrival: subtract(30, t=10) inserts at index 2! Updated sorted prefix up to t=30: 1. t=0 grant "base": heap = [[60, "base", 80]] 2. t=5 grant "promo": heap = [[25, "promo", 50], [60, "base", 80]] 3. t=10 sub 30: takes 30 from "promo" -> [[25, "promo", 20], [60, "base", 80]] 4. t=15 sub 65: takes 20 from "promo" (popped) + 45 from "base" -> [[60, "base", 35]] sum_unexpired(t=30): 60 > 30 -> 35Part 2: checkpoint heap snapshots every `interval` events
Replaying from index
0on everyget_balancecall costsO(N log N)even when two queries share almost the entire event prefix.Saving a snapshot (a deep copy of the grant min-heap) after every
interval(K) events lets any query jump straight to the furthest valid snapshot<= target_countand replay fewer thanKremaining events:interval K = 3: events index: 0 1 2 | 3 4 5 | 6 7 snapshots: [0] [1] [2] ^ ^ ^ 0 events events[:3] events[:6]Because
apply_eventdecrementsearliest_grant[2]in place,clone_grantsmust copy both the outer list and every inner[expiration, grant_id, remaining]list whenever reading or storing a snapshot. WithNevents, intervalK, andHunexpired grants per heap, snapshots useO((N / K) * H)memory.Invalidate only the suffix of snapshots after a late insertion
Suppose a late event inserts into
self.eventsat indexinsert_pos:- Snapshot
ksummarizesself.events[:k * K](indices0 .. k * K - 1). - Whenever
k * K <= insert_pos, the inserted event landed at or after indexk * K, leaving the prefixself.events[:k * K]completely untouched — snapshotkstays valid! - Whenever
k * K > insert_pos, snapshotkmissed the newly inserted event and must be discarded along with all later snapshots.
interval K = 3, late event inserts at insert_pos = 4: snapshots[0] -> events[:0] (0 <= 4: KEEP) snapshots[1] -> events[:3] (3 <= 4: KEEP) snapshots[2] -> events[:6] (6 > 4: DROP — missed index 4!) last_valid_snapshot = insert_pos // K = 4 // 3 = 1 del self.snapshots[last_valid_snapshot + 1:]Note also why the min-heap alone does not replace snapshots: the min-heap speeds up choosing the earliest-expiring grant within a single deduction (
O(log H)vsO(H)), whereas snapshots cut how many historical events each query replays (< KvsN). Combining both makes queries fast end-to-end.def clone_grants(grants: List[list]) -> List[list]: """Deep-copy the grant heap so replaying from a snapshot cannot mutate saved balances.""" copied_heap: List[list] = [] for expiration, grant_id, remaining in grants: copied_heap.append([expiration, grant_id, remaining]) return copied_heap class CheckpointedCreditLedger(CreditLedger): def __init__(self, interval: int = 64) -> None: super().__init__() if interval < 1: raise ValueError("interval must be at least 1") self.interval = interval self.snapshots: List[List[list]] = [[]] def _record(self, event: tuple) -> int: insert_pos = super()._record(event) last_valid_snapshot = insert_pos // self.interval del self.snapshots[last_valid_snapshot + 1:] return insert_pos def get_balance(self, timestamp: int) -> int: target_count = self._count_events_up_to(timestamp) snap_idx = min(target_count // self.interval, len(self.snapshots) - 1) grants = clone_grants(self.snapshots[snap_idx]) replayed = snap_idx * self.interval while replayed < target_count: apply_event(grants, self.events[replayed]) replayed += 1 if replayed == len(self.snapshots) * self.interval: self.snapshots.append(clone_grants(grants)) return sum_unexpired(grants, timestamp)- Snapshot
Complete solution
from typing import List import bisect import heapq # At the same timestamp, grants must apply before subtractions so a grant starting at time t # can immediately pay for usage at time t. Because GRANT (0) < SUBTRACT (1), Python's natural # tuple ordering places every grant at timestamp t ahead of every subtraction at timestamp t. GRANT = 0 SUBTRACT = 1 def apply_event(grants: List[list], event: tuple) -> None: """Apply a single sorted event to the active grant min-heap. grants: min-heap of [expiration, grant_id, remaining] lists ordered by (expiration, grant_id). event: (timestamp, kind, seq, amount, grant_id, expiration). """ timestamp, kind, _seq, amount, grant_id, expiration = event # Phase 1: A grant event simply adds a new [expiration, grant_id, remaining] entry to the heap. # Each entry is a list (not a tuple) so we can decrement `remaining` in place during usage. # Because `grant_id` is unique, two heap entries never tie on (expiration, grant_id), so # Python's heapq never compares index 2 (`remaining`) and in-place updates keep heap order valid. if kind == GRANT: heapq.heappush(grants, [expiration, grant_id, amount]) return # Phase 2: A subtraction event drains `needed` credits from the earliest-expiring active grants. needed = amount while needed > 0 and grants: earliest_grant = grants[0] grant_expiration = earliest_grant[0] # Expiration is exclusive (usable for start <= t < expiration), so `<=` means already expired. # Because replay visits events in non-decreasing timestamp order, a grant expired at # `timestamp` will stay expired for all later events too, so popping it permanently is safe. if grant_expiration <= timestamp: heapq.heappop(grants) continue # Spend as much as possible from this earliest-expiring grant before touching later ones. available_in_grant = earliest_grant[2] used = min(needed, available_in_grant) earliest_grant[2] -= used needed -= used # Remove exhausted grants right away so future subtractions and snapshots skip empty entries. if earliest_grant[2] == 0: heapq.heappop(grants) # If `needed > 0` after the heap empties, usage exceeded active credits. # Per the rules, we deduct everything available and drop the uncovered remainder (no debt). def sum_unexpired(grants: List[list], query_time: int) -> int: """Return total remaining credits among grants in `grants` that have not expired at `query_time`.""" total = 0 for expiration, _grant_id, remaining in grants: # Grants are only popped lazily during subtractions, so the heap may still contain grants # that expired after the last subtraction. Filter with `>` because expiration is exclusive. if expiration > query_time: total += remaining return total def clone_grants(grants: List[list]) -> List[list]: """Deep-copy the grant heap so replaying from a snapshot cannot mutate saved balances.""" copied_heap: List[list] = [] for expiration, grant_id, remaining in grants: copied_heap.append([expiration, grant_id, remaining]) return copied_heap class CreditLedger: """Part 1: Keep recorded events sorted by replay order and replay from time zero per query.""" def __init__(self) -> None: # events: sorted list of (timestamp, kind, seq, amount, grant_id, expiration) tuples self.events: List[tuple] = [] # grant_ids: set of already-registered grant IDs to reject duplicates in O(1) time self.grant_ids = set() # next_seq: monotonically increasing arrival counter so same-(timestamp, kind) ties are deterministic self.next_seq = 0 def add_credit(self, grant_id: str, amount: int, timestamp: int, expiration: int) -> None: # Validate all inputs before mutating state so a rejected call leaves no partial changes. if grant_id in self.grant_ids: raise ValueError(f"duplicate grant id {grant_id!r}") if amount <= 0: raise ValueError("amount must be positive") if expiration <= timestamp: raise ValueError("a grant must expire after it starts") self.grant_ids.add(grant_id) seq = self.next_seq self.next_seq += 1 event = (timestamp, GRANT, seq, amount, grant_id, expiration) self._record(event) def subtract(self, amount: int, timestamp: int) -> None: if amount <= 0: raise ValueError("amount must be positive") seq = self.next_seq self.next_seq += 1 event = (timestamp, SUBTRACT, seq, amount, None, None) self._record(event) def get_balance(self, timestamp: int) -> int: # Replay the prefix of events with event_timestamp <= timestamp from an empty heap. event_count = self._count_events_up_to(timestamp) grants: List[list] = [] for idx in range(event_count): apply_event(grants, self.events[idx]) return sum_unexpired(grants, timestamp) def _record(self, event: tuple) -> int: """Insert `event` into `self.events` in sorted replay order and return its index.""" insert_pos = bisect.bisect_right(self.events, event) self.events.insert(insert_pos, event) return insert_pos def _count_events_up_to(self, timestamp: int) -> int: """Return how many recorded events have event_timestamp <= `timestamp`.""" # Every real event at `timestamp` has kind == 0 (GRANT) or kind == 1 (SUBTRACT). # Using kind == SUBTRACT + 1 (2) makes `probe` sort strictly after all events at `timestamp` # and strictly before all events at `timestamp + 1`, without comparing past index 1. probe = (timestamp, SUBTRACT + 1) return bisect.bisect_right(self.events, probe) class CheckpointedCreditLedger(CreditLedger): """Part 2: Save heap snapshots every `interval` events and invalidate only affected suffix snapshots.""" def __init__(self, interval: int = 64) -> None: super().__init__() if interval < 1: raise ValueError("interval must be at least 1") self.interval = interval # snapshots[k] holds a deep copy of the grant heap after replaying `self.events[:k * interval]`. # snapshots[0] is always `[]` (the empty heap after 0 events). self.snapshots: List[List[list]] = [[]] def _record(self, event: tuple) -> int: insert_pos = super()._record(event) # Snapshot k summarizes `events[:k * interval]` (indices 0 .. k * interval - 1). # Inserting at `insert_pos` leaves that prefix unchanged iff `k * interval <= insert_pos`, # which is `k <= insert_pos // self.interval`. Discard every snapshot after that index. last_valid_snapshot = insert_pos // self.interval del self.snapshots[last_valid_snapshot + 1:] return insert_pos def get_balance(self, timestamp: int) -> int: target_count = self._count_events_up_to(timestamp) # Resume from the furthest already-built snapshot that does not overshoot `target_count`. snap_idx = min(target_count // self.interval, len(self.snapshots) - 1) grants = clone_grants(self.snapshots[snap_idx]) replayed = snap_idx * self.interval # Replay only the remaining tail of events, saving new snapshots whenever we cross a boundary. while replayed < target_count: apply_event(grants, self.events[replayed]) replayed += 1 if replayed == len(self.snapshots) * self.interval: self.snapshots.append(clone_grants(grants)) return sum_unexpired(grants, timestamp)✅ Submit now — all tests should pass.
Intuition & how it works
Think of an account holding several prepaid vouchers, each valid from a start timestamp until an expiration timestamp. Every purchase spends from whichever active voucher expires soonest so long-lived vouchers are preserved. The twist is that vouchers and receipts can arrive out of chronological order, and callers can ask for the available balance at any historical or future timestamp t.
Maintaining a single running integer balance fails as soon as an out-of-order event arrives: a delayed Tuesday receipt can consume a short-lived voucher before Wednesday's charge runs, pushing Wednesday's charge onto a longer-lived voucher and lowering Friday's balance. Replaying all events up to t in timestamp order with a min-heap (a priority structure keeping the earliest-expiring voucher on top in O(log H) time) guarantees exact balances, while saving periodic snapshots (deep copies of the heap every K events) lets queries skip unchanged prefixes and invalidates only the suffix of snapshots after a late insertion.
Trace Example 1 with checkpoint interval K = 2:
1. Log "base" (80 credits, [0, 60)), "promo" (50 credits, [5, 25)), and subtract(65, t=15). Sorted events: [base@0, promo@5, sub65@15].
2. Query get_balance(30): replaying from snapshots[0] = [] saves snapshots[1] = [[25, "promo", 50], [60, "base", 80]] after index 1, then applies sub65@15 (50 from "promo", 15 from "base"), returning 65.
3. Late subtract(30, t=10) inserts at index 2 ([base@0, promo@5, sub30@10, sub65@15]). Because snapshots[1] summarizes indices 0..1, it remains valid (2 // 2 == 1)!
4. Query get_balance(30) again: clone snapshots[1], skip the first two events, and replay only sub30@10 ("promo" drops to 20) and sub65@15 ("promo" gives 20, "base" gives 45), returning 35.
Complexity
Let N be the total number of logged events, H be the number of unexpired grants inside a snapshot heap (H <= N), and K be the checkpoint interval.
- Logging (
add_credit/subtract):O(N)time. Binary search (repeatedly halvingself.eventsto locateinsert_pos) takesO(log N)comparisons,list.insertshifts up toNtuple references inO(N)time, and Part 2 truncates at mostN / Kinvalidated snapshot pointers. - Part 1
get_balance:O(N log N)time andO(H)space. Binary search locates the prefix inO(log N)time; across the replay, each grant is pushed once and popped at most once (O(log H)per heap operation), each partial deduction updatesgrants[0]inO(1)time, and summing surviving grants takesO(H). - Part 2
get_balance(warm snapshots):O(log N + H + (K + D) log(H + K))time, whereD <= H + Kis how many grants expire or reach zero during the< Kreplayed tail events:O(log N)binary search,O(H)to deep-copy one snapshot, at mostKheap pushes andDpops, andO(H + K)to sum unexpired credits. - Part 2
get_balanceafter a late event at indexp: ReplayingM = target_count - (p // K) * Kevents rebuilds roughlyM / Ksnapshots inO((H + M) log(H + M) + (M / K) * H)time. - Space:
O(N)for Part 1, andO(N + (N / K) * H)for Part 2 to store up to1 + N // Kheap snapshots.
Edge cases
- Empty ledger or query earlier than every event:
_count_events_up_to(t)returns0andget_balance(t)returns0. - Exact interval boundaries (
startinclusive,expirationexclusive): A grant on[5, 25)counts att = 5andt = 24, but contributes0att = 25and cannot fundsubtract(..., 25). - Same-timestamp grant and deduction: Setting
GRANT = 0 < SUBTRACT = 1ensures all grants starting attenter the heap before any deduction attexecutes. - Overdraft above active credits: Drains active grants to
0and drops the excess without affecting grants that start at later timestamps. - Late event preceding all prior events (
insert_pos = 0): Keepssnapshots[0] = [](0 // K == 0) and dropssnapshots[1:]. - Invalid arguments (
ValueError): Checked upfront before mutatinggrant_ids,events, orsnapshots.
Common mistakes
- Mutating a single running balance in arrival order: Produces wrong historical and future balances whenever a late deduction or short-lived grant shifts which grant funded an intermediate deduction.
- Shallow-copying snapshots (
list(snapshot)): Shares the inner[expiration, grant_id, remaining]lists across queries, allowingearliest_grant[2] -= usedduring one query to corrupt saved snapshots. - Off-by-one snapshot invalidation: Dropping
snapshots[insert_pos // K]discards a valid prefix, while keepingsnapshots[insert_pos // K + 1]reuses stale state that missed the inserted event. - Caching scalar balances instead of grant heaps: Knowing the balance was
100att = 12is insufficient to resume att = 15, because replay must know that20expires at25while80expires at60. - Probing
bisect_rightwith a 1-tuple(timestamp,): A 1-tuple(t,)sorts before every 6-tuple starting witht, skipping all events stamped att.
Alternative approaches
- Time-bucketed checkpoints (e.g., every 60 time units): Easy to invalidate by timestamp, but an intense burst of
50,000events at one timestamp forces queries in that bucket to replay all50,000events; indexing checkpoints everyKevents guarantees bounded replay length under bursty traffic. - Balanced BST or skip list for
events: Lowers out-of-order insertion fromO(N)array shifting toO(log N)if write throughput reaches millions of out-of-order events.
Follow-up questions
- If writes usually arrive in chronological order and callers mostly query the current timestamp, how can you answer those live-edge queries in nearly O(1) time? Maintain a live "head" state alongside the periodic snapshots: the grant min-heap after all logged events plus an integer
active_sumholding the sum of credits currently in that heap. When a write arrives in chronological order (insert_pos == len(events) - 1), apply it directly to the head heap inO(log H)time; if an out-of-order write lands earlier, mark the head state dirty and lazily rebuild it from the last valid snapshot on the next head query. At the latest event timestampt_latest, pop expired entries (expiration <= t_latest, lazy expiry — deferring cleanup until queried) while subtracting them fromactive_suminO(1)amortized time per grant; fort > t_latest, traverse heap nodes withexpiration <= twithout popping (since a future event betweent_latestandtcould still consume them) and subtract their sum fromactive_sum. - Suppose producers guarantee a bounded clock-skew window D so no event ever arrives more than D time units late. How can you use that bound to prune historical state? Maintain a watermark
W = max_timestamp_seen - D(a monotonic cutoff below which no valid future write can arrive). Every snapshot whose final covered event hastimestamp < Wis permanently immutable. You can promote the newest immutable snapshot to be your new base state, discard all older snapshots and raw events covered by that prefix to bound RAM, and either reject or send to an offline dead-letter reconciliation log any straggler violatingtimestamp < W. - What changes are needed to let callers void or roll back a previously recorded deduction? Return a unique monotonic
seqID fromsubtractand store a lookup mapseq -> (timestamp, SUBTRACT, seq)socancel_subtract(seq)can binary-search and remove that exact tuple atremove_posinself.events. Deleting atremove_posleavesself.events[:k * K]unchanged wheneverk * K <= remove_pos, so snapshot invalidation uses the exact same ruledel self.snapshots[remove_pos // self.interval + 1:](always generatingseqfrom a monotonic counterself.next_seq, neverlen(self.events)). - To make the ledger crash-safe across process restarts, should you write the raw event log, the periodic snapshots, or both to durable storage? Always persist the raw events to an append-only write-ahead log (a durable log where each event is flushed before acknowledging the caller), because the raw event stream is the authoritative source of truth needed to recompute balances when late events rewrite history. Checkpoints are derived caches: persisting periodic snapshots tagged with the sort key of their last covered event is optional, but doing so cuts restart recovery from replaying months of events down to loading one recent valid snapshot and replaying only the short log tail after it.
Follow-up questions
- If writes usually arrive in chronological order and callers mostly query the current timestamp, how can you answer those live-edge queries in nearly O(1) time?
- Suppose producers guarantee a bounded clock-skew window D so no event ever arrives more than D time units late. How can you use that bound to prune historical state?
- What changes are needed to let callers void or roll back a previously recorded deduction?
- To make the ledger crash-safe across process restarts, should you write the raw event log, the periodic snapshots, or both to durable storage?
Similar questions
- Asymptotic Time and Space Analysis of Dense Matrix Multiplication
- In-Memory Task Queue with Leases, Retries, Dead-Lettering, and Prerequisites
- Architecting a Fault-Tolerant Streaming Chat Client
- Expiring Usage-Credit Ledger Under Out-of-Order Events
- Cluster Interconnect Component and Topology Analyzer
- Directed Social Graph with Snapshots and Recommendations
More OpenAI interview questions
- Minimum Removals to Contain Grid Blight Medium
- Technical Project Deep Dive and Architecture Trade-Off Defense Medium
- Design a Fault-Tolerant Merchant Payment and Refund Platform Hard Pro
- Why OpenAI? Medium Pro
- Snapshot-Queryable Follow Graph Hard Pro
- Design a Stateless Token-Streaming LLM Inference Service Hard Pro
- Design a Real-Time Multiplayer Chess Service Hard Pro
- Cluster Tree Topology Summary Medium Pro
- Design a Fault-Tolerant Asynchronous Video-Generation Service Hard Pro
- Grid Load-Curtailment Control Plane Hard Pro