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

  1. Part 1 — CreditLedger:

    • add_credit(grant_id: str, amount: int, timestamp: int, expiration: int) -> None: Registers a credit grant identified by grant_id holding amount credits, active on the half-open window timestamp <= t < expiration (usable starting at timestamp, expired at expiration).
    • subtract(amount: int, timestamp: int) -> None: Logs a deduction of amount credits occurring at timestamp.
    • get_balance(timestamp: int) -> int: Computes the total unused, unexpired credit available at timestamp after applying every logged event with event time <= timestamp in chronological order, regardless of arrival order.
  2. Ordering, Tie-Breaking, Overdraft, and Validation Rules:

    • Same-timestamp ordering: When grants and deductions share the exact same timestamp t, all grants starting at t take effect before any deduction at t. Multiple deductions at t apply in arrival order.
    • Earliest-expiration-first consumption: A deduction at time t draws from currently active grants (start <= t < expiration) ordered by smallest expiration first. Ties in expiration are broken by lexicographically smallest grant_id.
    • Capped overdraft (no debt): If a deduction at time t exceeds total active credits at t, every active grant is drained to 0 and the uncovered remainder is discarded — balances never go negative and future grants are unaffected.
    • Validation: add_credit raises ValueError if grant_id was already used, amount <= 0, or expiration <= timestamp (leaving ledger state untouched on error). subtract raises ValueError if amount <= 0.
  3. Part 2 — CheckpointedCreditLedger(interval: int = 64):

    • Exposes the exact same methods and results as CreditLedger (raising ValueError if interval < 1), but stores periodic state checkpoints every interval events so get_balance resumes from the nearest valid checkpoint rather than replaying from event 0, discarding only checkpoints invalidated when an out-of-order event inserts earlier in the timeline.
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

  • timestamp and expiration are integers with timestamp < expiration for valid grants.
  • amount >= 1 for valid add_credit and subtract calls.
  • grant_id is a unique string across all successful add_credit calls on a ledger instance.
  • interval >= 1 for CheckpointedCreditLedger.

Step-by-step walkthrough

  1. 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 at timestamp (inclusive) and expires at expiration (exclusive). At t == expiration, its remaining credits are already expired.
    • Same-timestamp ordering: Grants starting at t take effect before deductions at t, allowing a grant that activates at t to fund a deduction at t. Multiple deductions at t apply in the order they were logged.
    • Equal-expiration tie-breaker: When two active grants expire at the same timestamp, consume from the smaller grant_id first ("g1" < "g2").
    • Capped overdraft: When a deduction requests more credits than all currently active grants hold, drain active grants to 0 and discard the uncovered excess — never carry negative balances or future debt. Notice why subtract cannot raise on insufficient funds when logged: a grant covering that timestamp might arrive later out of order.
    • Input validation: Raise ValueError for duplicate grant_id, amount <= 0, expiration <= timestamp, or interval < 1.
  2. Keep events sorted in chronological replay order

    Because add_credit and subtract calls 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 inside self.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 <= t forms a contiguous prefix self.events[:event_count]. We locate event_count in O(log N) time via bisect.bisect_right with the 2-tuple probe (t, SUBTRACT + 1):

    events:  (5, 0, ...)  (10, 0, ...)  (10, 1, ...) | (15, 1, ...)
                                                     ^
             probe = (10, 2) lands here -> event_count = 3
    

    Because every real event at timestamp 10 has kind equal to 0 or 1 (< 2), and every event at 11+ has a larger index-0 timestamp, Python stops comparing at index 1 and 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)
    
  3. 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 0 with O(log H) push/pop) provides that directly.

    Represent each heap entry as a 3-element list [expiration, grant_id, remaining]:

    1. Why a mutable list? Partial deductions decrement remaining in place (earliest_grant[2] -= used). Because grant_id is unique, two entries never tie on (expiration, grant_id), so heapq never compares index 2 and in-place decrements preserve the heap invariant.
    2. Lazy eviction of expired grants: When processing a deduction at timestamp, if grants[0] has expiration <= 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.
    3. Final unexpired sum: Grants that expire after the last deduction remain in the heap when replay stops, so sum_unexpired filters entries with expiration > 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
    
  4. Complete Part 1 and trace Example 1

    Validate all arguments in add_credit before mutating self.grant_ids so 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 -> 35
    
  5. Part 2: checkpoint heap snapshots every `interval` events

    Replaying from index 0 on every get_balance call costs O(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_count and replay fewer than K remaining 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_event decrements earliest_grant[2] in place, clone_grants must copy both the outer list and every inner [expiration, grant_id, remaining] list whenever reading or storing a snapshot. With N events, interval K, and H unexpired grants per heap, snapshots use O((N / K) * H) memory.

  6. Invalidate only the suffix of snapshots after a late insertion

    Suppose a late event inserts into self.events at index insert_pos:

    • Snapshot k summarizes self.events[:k * K] (indices 0 .. k * K - 1).
    • Whenever k * K <= insert_pos, the inserted event landed at or after index k * K, leaving the prefix self.events[:k * K] completely untouched — snapshot k stays valid!
    • Whenever k * K > insert_pos, snapshot k missed 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) vs O(H)), whereas snapshots cut how many historical events each query replays (< K vs N). 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)
    
  7. 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 halving self.events to locate insert_pos) takes O(log N) comparisons, list.insert shifts up to N tuple references in O(N) time, and Part 2 truncates at most N / K invalidated snapshot pointers.
  • Part 1 get_balance: O(N log N) time and O(H) space. Binary search locates the prefix in O(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 updates grants[0] in O(1) time, and summing surviving grants takes O(H).
  • Part 2 get_balance (warm snapshots): O(log N + H + (K + D) log(H + K)) time, where D <= H + K is how many grants expire or reach zero during the < K replayed tail events: O(log N) binary search, O(H) to deep-copy one snapshot, at most K heap pushes and D pops, and O(H + K) to sum unexpired credits.
  • Part 2 get_balance after a late event at index p: Replaying M = target_count - (p // K) * K events rebuilds roughly M / K snapshots in O((H + M) log(H + M) + (M / K) * H) time.
  • Space: O(N) for Part 1, and O(N + (N / K) * H) for Part 2 to store up to 1 + N // K heap snapshots.

Edge cases

  • Empty ledger or query earlier than every event: _count_events_up_to(t) returns 0 and get_balance(t) returns 0.
  • Exact interval boundaries (start inclusive, expiration exclusive): A grant on [5, 25) counts at t = 5 and t = 24, but contributes 0 at t = 25 and cannot fund subtract(..., 25).
  • Same-timestamp grant and deduction: Setting GRANT = 0 < SUBTRACT = 1 ensures all grants starting at t enter the heap before any deduction at t executes.
  • Overdraft above active credits: Drains active grants to 0 and drops the excess without affecting grants that start at later timestamps.
  • Late event preceding all prior events (insert_pos = 0): Keeps snapshots[0] = [] (0 // K == 0) and drops snapshots[1:].
  • Invalid arguments (ValueError): Checked upfront before mutating grant_ids, events, or snapshots.

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, allowing earliest_grant[2] -= used during one query to corrupt saved snapshots.
  • Off-by-one snapshot invalidation: Dropping snapshots[insert_pos // K] discards a valid prefix, while keeping snapshots[insert_pos // K + 1] reuses stale state that missed the inserted event.
  • Caching scalar balances instead of grant heaps: Knowing the balance was 100 at t = 12 is insufficient to resume at t = 15, because replay must know that 20 expires at 25 while 80 expires at 60.
  • Probing bisect_right with a 1-tuple (timestamp,): A 1-tuple (t,) sorts before every 6-tuple starting with t, skipping all events stamped at t.

Alternative approaches

  • Time-bucketed checkpoints (e.g., every 60 time units): Easy to invalidate by timestamp, but an intense burst of 50,000 events at one timestamp forces queries in that bucket to replay all 50,000 events; indexing checkpoints every K events guarantees bounded replay length under bursty traffic.
  • Balanced BST or skip list for events: Lowers out-of-order insertion from O(N) array shifting to O(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_sum holding 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 in O(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 timestamp t_latest, pop expired entries (expiration <= t_latest, lazy expiry — deferring cleanup until queried) while subtracting them from active_sum in O(1) amortized time per grant; for t > t_latest, traverse heap nodes with expiration <= t without popping (since a future event between t_latest and t could still consume them) and subtract their sum from active_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 has timestamp < W is 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 violating timestamp < W.
  • What changes are needed to let callers void or roll back a previously recorded deduction? Return a unique monotonic seq ID from subtract and store a lookup map seq -> (timestamp, SUBTRACT, seq) so cancel_subtract(seq) can binary-search and remove that exact tuple at remove_pos in self.events. Deleting at remove_pos leaves self.events[:k * K] unchanged whenever k * K <= remove_pos, so snapshot invalidation uses the exact same rule del self.snapshots[remove_pos // self.interval + 1:] (always generating seq from a monotonic counter self.next_seq, never len(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

Similar questions

More OpenAI interview questions

All 493 OpenAI questions →