GPU Credits / GPU Credit 2

Medium · Coding · 75 min

Implement a GPU credit ledger GPUCredit. The platform grants GPU credits to users, where each grant has an activation timestamp and a validity duration; GPU usage deducts credits; and callers query the available balance at any timestamp. Across all 4 parts, the interface consists of the same three methods:

class GPUCredit:
    def add_credit(self, credit_id: str, amount: int, timestamp: int, expiration: int) -> None: ...
    def subtract(self, amount: int, timestamp: int) -> None: ...
    def get_balance(self, timestamp: int) -> int | None: ...

All timestamps and amounts are integers.

Part 1: Credit Grants and Balance Queries

  • add_credit(credit_id, amount, timestamp, expiration): Grants amount credits valid on the closed interval [timestamp, timestamp + expiration] (usable through the expiration timestamp itself, and expired starting at the next timestamp).
  • credit_id must be unique. A duplicate credit_id, amount < 0, or expiration < 0 must raise ValueError without recording the failed call (so the same unused ID can still be granted later).
  • get_balance(t): Returns the sum of remaining credits across all grants active at timestamp t.
  • If no grant is active at timestamp t, return None. If at least one grant is active at t and the remaining balance is zero (e.g., an amount = 0 grant), return 0.

In Parts 1–3, all calls (including get_balance) arrive in non-decreasing timestamp order.

g = GPUCredit()
g.add_credit("a", 10, 0, 5)     # active on [0, 5]
g.add_credit("b", 5, 3, 10)     # active on [3, 13]
g.get_balance(5)                # 15
g.get_balance(6)                # 5, since "a" has expired
g.get_balance(14)               # None

Part 2: Deductions — Earliest Expiration First

subtract(amount, timestamp): Deducts amount at timestamp (amount < 0 raises ValueError).

  • Credits can only be deducted from grants active at timestamp.
  • Consume from the active grant with the earliest expiration timestamp first; if it is insufficient, continue to the next earliest-expiring grant, spanning multiple grants as needed.
  • Consumed credits are permanently spent: once an earlier-expiring grant later expires, credits deducted from it are never "refunded" back to other grants.
  • If grants and deductions share the exact same timestamp, process grants before deductions.
g = GPUCredit()
g.add_credit("a", 4, 1, 8)      # active on [1, 9]
g.add_credit("b", 3, 2, 2)      # active on [2, 4]
g.subtract(2, 3)                # "b" expires earlier, so deduct 2 from "b"
g.get_balance(4)                # 5  (a: 4 + b: 1)
g.get_balance(5)                # 4  ("b" expired; its unused 1 is forfeited)

Part 3: Overdraft Debt and None Semantics

  • If a deduction exceeds the total active balance at that timestamp, the uncovered remainder is recorded as debt.
  • Every subsequent grant pays down existing debt first, and only the leftover amount enters available credit. If multiple grants share the same timestamp, earlier-expiring grants pay down debt first.
  • Debt never expires with time; it can only be cleared by subsequent grants.
  • get_balance(t): Returns None if unpaid debt remains at t or no grant is active at t; otherwise returns the remaining active balance (0 when active grants have been completely used up).
g = GPUCredit()
g.add_credit("a", 5, 0, 10)
g.subtract(8, 1)                # leaves debt of 3
g.get_balance(2)                # None
g.add_credit("b", 10, 3, 10)    # repays 3 debt first, leaving 7 available
g.get_balance(3)                # 7

Part 4: Out-of-Order Events (GPU Credit 2)

Drop the monotonic-arrival assumption from Parts 1–3: add_credit, subtract, and get_balance may now arrive in any order, and get_balance(t) is evaluated strictly by event timestamp:

  • A query at timestamp t depends only on events with timestamp <= t; future events must never leak into earlier balances.
  • Late-arriving historical events take effect at their event timestamp and may retroactively change which grants absorbed later deductions.
  • Regardless of arrival order, the same set of events must always produce identical query answers (which is why Part 3 defines deterministic tie-breaking at identical timestamps).

Self-test example: Grant 4 at t = 1 (valid through 9), grant 3 at t = 2 (valid through 4), and deduct 2 at t = 3. Even if subtract(2, 3) arrives first, querying t = 4 must return 5, t = 5 must return 4, and t = 2 must return 7.

g = GPUCredit()
g.subtract(2, 3)                # arrives first
g.add_credit("a", 4, 1, 8)
g.add_credit("b", 3, 2, 2)
g.get_balance(4), g.get_balance(5)   # (5, 4)

Clarifying Questions to Ask in an Interview

  • Is the expiration boundary inclusive or exclusive? Is expiration a duration or an absolute timestamp?
  • What happens when a deduction exceeds available balance: reject it, clamp at 0, or track overdraft debt? Do future grants pay off past overdrafts?
  • Should zero remaining balance be distinguished from having no active grants (0 vs None)?
  • At the same timestamp, are grants processed before deductions? Among simultaneous grants, which one repays debt first?
  • Do events arrive in chronological order, and can queries ask about past timestamps?
  • What is the scale of events vs. queries — do we need something faster than replaying all events per query?

Step-by-step walkthrough

  1. Part 1 · Core idea: log raw events and replay on query

    A user's GPU balance at timestamp t depends on the entire history of grants and debits up to t: which grants were active when each debit happened, which ones expired unused, and whether any debt is still owed. The cleanest and least error-prone architecture is event replay:

    • add_credit and subtract only validate inputs and append the raw event to a list.
    • get_balance(t) collects all events with event_time <= t, sorts them into chronological order, and simulates them from start to finish.
    Recorded events:  t=1 grant a(4, ends 9)    t=2 grant b(3, ends 4)    t=3 debit 2
    
    get_balance(4):   replay t=1, 2, 3 -> debit spends 2 from earlier-expiring b
                      at t=4: a has 4, b has 1 (still valid since 4 <= 4)  --> returns 5
    get_balance(5):   replay t=1, 2, 3 -> at t=5, b has expired (4 < 5)
                      only a remains with 4                                --> returns 4
    

    Replaying from scratch on every query keeps the code short and transparent, and as a bonus it will handle Part 4's out-of-order arrivals automatically because replay sorts by event time, not arrival order.

  2. Part 1 · Validate and record credit grants

    Each credit_id must be unique, and negative amount or expiration must raise ValueError without registering the ID. That means we must run every validation check before calling self.used_ids.add(credit_id), so a rejected call never blocks a future valid call with the same credit_id.

    Since a grant is valid on the closed interval [timestamp, timestamp + expiration], we store (start_time, end_time, amount) directly.

    class GPUCredit:
        def __init__(self):
            # grants: list of (start_time, end_time, amount) tuples; valid on [start_time, end_time]
            self.grants = []
            # debits: list of (debit_time, amount) tuples
            self.debits = []
            # used_ids: set of credit_id strings that passed validation
            self.used_ids = set()
    
        def add_credit(
            self, credit_id: str, amount: int, timestamp: int, expiration: int
        ) -> None:
            if credit_id in self.used_ids:
                raise ValueError(f"duplicate credit id: {credit_id}")
            if amount < 0 or expiration < 0:
                raise ValueError("amount and expiration must be >= 0")
    
            self.used_ids.add(credit_id)
            end_time = timestamp + expiration
            self.grants.append((timestamp, end_time, amount))
    
  3. Part 1 · Sum valid grants and distinguish `0` from `None`

    In Part 1 there are no debits yet, so the balance at timestamp is simply the sum of all grants whose [start_time, end_time] interval contains timestamp.

    Pay careful attention to None versus 0: - If no grant covers timestamp, return None. - If at least one grant covers timestamp — even a grant with amount == 0 — return 0 (or the positive sum).

    We write has_valid_grant(timestamp) as its own helper because Parts 2–4 will reuse the exact same check.

    def has_valid_grant(self, timestamp: int) -> bool:
        """Return True if at least one grant's [start_time, end_time] covers `timestamp`."""
        for start_time, end_time, _ in self.grants:
            if start_time <= timestamp <= end_time:
                return True
        return False
    
    
    def get_balance(self, timestamp: int) -> int | None:
        if not self.has_valid_grant(timestamp):
            return None
        total_balance = 0
        for start_time, end_time, amount in self.grants:
            if start_time <= timestamp <= end_time:
                total_balance += amount
        return total_balance
    

    ✅ Submit now — Part 1 tests should pass.

  4. Part 2 · Record debits and sort events into deterministic replay order

    subtract simply checks amount >= 0 and logs (timestamp, amount). To replay grants and debits together, we pack every event with time <= timestamp into a 4-tuple (event_time, event_kind, end_time, amount) and call Python's built-in .sort():

    Tuple layout:  (event_time, event_kind, end_time, amount)
                        |            |          |
                        |            |          +-- 3rd: earlier-expiring grants first (for Part 3 debt)
                        |            +------------- 2nd: GRANT (0) before DEBIT (1) at same timestamp
                        +-------------------------- 1st: chronological order
    

    Filtering to <= timestamp guarantees future events never leak into historical balance queries.

    GRANT = 0
    DEBIT = 1
    
    
    class GPUCredit:
        # ... __init__, add_credit, has_valid_grant ...
    
        def subtract(self, amount: int, timestamp: int) -> None:
            if amount < 0:
                raise ValueError("amount must be >= 0")
            self.debits.append((timestamp, amount))
    
        def collect_sorted_events(
            self, timestamp: int
        ) -> list[tuple[int, int, int, int]]:
            events = []
            for start_time, end_time, amount in self.grants:
                if start_time <= timestamp:
                    events.append((start_time, GRANT, end_time, amount))
            for debit_time, amount in self.debits:
                if debit_time <= timestamp:
                    events.append((debit_time, DEBIT, 0, amount))
            events.sort()
            return events
    
  5. Part 2 · Replay grants and earliest-expiry-first debits

    During replay, we keep a list active_grants where each entry is a two-element list [end_time, remaining_amount]. At every event with timestamp event_time:

    1. Prune expired grants first: keep only entries with end_time >= event_time. Why prune before every event instead of only at the end of get_balance? Because if grant a expired at t = 2, a debit at t = 4 must skip a and deduct from b instead!
    2. If GRANT: append [end_time, amount] to active_grants.
    3. If DEBIT: sort active_grants so the smallest end_time comes first, and walk through the list deducting min(grant[1], remaining_to_spend) until the debit is satisfied.

    After the loop finishes, prune once more at the query timestamp and sum what remains.

    def prune_expired(
        active_grants: list[list[int]], current_time: int
    ) -> list[list[int]]:
        """Keep only grants whose inclusive end_time is still >= current_time."""
        still_valid = []
        for grant in active_grants:
            end_time = grant[0]
            if end_time >= current_time:
                still_valid.append(grant)
        return still_valid
    
    def get_balance(self, timestamp: int) -> int | None:
        active_grants = []
    
        for event_time, event_kind, end_time, amount in self.collect_sorted_events(timestamp):
            active_grants = prune_expired(active_grants, event_time)
    
            if event_kind == GRANT:
                active_grants.append([end_time, amount])
            else:
                active_grants.sort()
                remaining_to_spend = amount
                for grant in active_grants:
                    if remaining_to_spend == 0:
                        break
                    used = min(grant[1], remaining_to_spend)
                    grant[1] -= used
                    remaining_to_spend -= used
    
        active_grants = prune_expired(active_grants, timestamp)
        if not self.has_valid_grant(timestamp):
            return None
    
        total_balance = 0
        for end_time, remaining in active_grants:
            total_balance += remaining
        return total_balance
    

    Notice we leave [end_time, 0] entries inside active_grants when a grant is fully spent — adding 0 at the end does not change total_balance, and has_valid_grant(timestamp) still correctly returns 0 (not None) while that grant's time window is active.

    ✅ Submit now — Part 2 tests should pass.

  6. Part 3 · Track overdraft debt and repay it with new grants

    Part 3 requires only three small additions inside get_balance:

    1. Create debt: After scanning all active_grants for a debit, any leftover remaining_to_spend is added to debt.
    2. Repay debt: When a GRANT arrives, repaid = min(debt, amount) pays down debt first, and only amount - repaid enters active_grants. Because collect_sorted_events already sorted simultaneous grants by end_time, earlier-expiring grants automatically repay debt first!
    3. Return None while in debt: At the end, if debt > 0 or not self.has_valid_grant(timestamp): return None.
    Overdraft trace:
    t=0: grant a(5, ends 10)   -> debt=0, active=[[10, 5]]
    t=1: debit 8               -> uses 5 from a, 3 uncovered -> debt=3, active=[[10, 0]]
         get_balance(2)        -> debt=3 > 0 -> None
    t=3: grant b(10, ends 13)  -> repaid=min(3,10)=3 -> debt=0, active=[[10, 0], [13, 7]]
         get_balance(3)        -> debt=0 and valid grant exists -> 7
    
    def get_balance(self, timestamp: int) -> int | None:
        active_grants = []
        debt = 0
    
        for event_time, event_kind, end_time, amount in self.collect_sorted_events(timestamp):
            # Step 1: Drop grants that expired before this event occurred.
            active_grants = prune_expired(active_grants, event_time)
    
            if event_kind == GRANT:
                # Step 2 (Grant): Repay any existing overdraft debt first; keep the remainder.
                repaid = min(debt, amount)
                debt -= repaid
                remaining = amount - repaid
                active_grants.append([end_time, remaining])
            else:
                # Step 3 (Debit): Spend from earliest-expiring valid grants first.
                active_grants.sort()
                remaining_to_spend = amount
                for grant in active_grants:
                    if remaining_to_spend == 0:
                        break
                    used = min(grant[1], remaining_to_spend)
                    grant[1] -= used
                    remaining_to_spend -= used
                debt += remaining_to_spend
    
        # Step 4: Drop grants expired before `timestamp`, then check debt and validity.
        active_grants = prune_expired(active_grants, timestamp)
        if debt > 0 or not self.has_valid_grant(timestamp):
            return None
    
        total_balance = 0
        for end_time, remaining in active_grants:
            total_balance += remaining
        return total_balance
    

    ✅ Submit now — Part 3 tests should pass.

  7. Part 4 · Verify why out-of-order events already work

    In Part 4, add_credit, subtract, and get_balance can arrive in any order. Let's verify every guarantee in our design:

    1. Arrival order is ignored: add_credit and subtract only append tuples; neither touches any running balance.
    2. Deterministic tie-breaking: collect_sorted_events sorts by (event_time, event_kind, end_time, amount). Even if two grants arrive at the same event_time in reverse order, the earlier-expiring one always repays debt first; if two grants also share the exact same end_time, every remaining credit unit expires at the same moment anyway.
    3. No future leakage: start_time <= timestamp and debit_time <= timestamp filter out everything after timestamp.
    Arrival order:  1st subtract(2, t=3)   2nd add("a", 4, t=1..9)   3rd add("b", 3, t=2..4)
    
    Replay for get_balance(2):  events <= 2 are [t=1 a(4), t=2 b(3)] (t=3 debit excluded!) -> 7
    Replay for get_balance(4):  events <= 4 are [t=1 a(4), t=2 b(3), t=3 debit(2)]         -> 5
    Replay for get_balance(5):  same replay, then prune at t=5 drops b (end 4 < 5)         -> 4
    

    Zero lines of code need to change for Part 4.

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of GPU credits like a stack of store gift cards with different expiration dates: whenever you buy something, a smart cashier spends from the gift card that expires soonest so your longer-lasting cards stay intact. If your mail arrives out of order — say a restaurant receipt from Wednesday shows up before the gift card you actually received on Tuesday — you cannot just maintain one live wallet total; instead, you lay every card and receipt on a table sorted by date and replay them from Monday forward. That pattern is called event replay (or event sourcing, meaning we store an append-only log of raw events and compute the state at any timestamp t by re-running events in chronological order).

Why do simpler formulas fall apart? You cannot compute the balance as total_valid_grants - total_debits because which grant absorbed an earlier debit changes what expires later: if a short-lived grant paid for yesterday's job and then expired today, your long-lived grant is still completely untouched! Similarly, maintaining only a single running state works when timestamps strictly increase (Parts 1–3), but breaks immediately in Part 4 when a backdated grant arrives late and retroactively absorbs a past debit that had previously eaten into a long-lived grant or created debt.

Let's walk through the out-of-order example where subtract(2, t=3) arrives first, followed by a (4 credits on the closed interval [1, 9], meaning both endpoints t=1 and t=9 are included) and b (3 credits on [2, 4]):

Sorted events <= 5:
  1. (t=1, GRANT, end=9, amt=4)  -> debt=0; active_grants = [[9, 4]]
  2. (t=2, GRANT, end=4, amt=3)  -> debt=0; active_grants = [[9, 4], [4, 3]]
  3. (t=3, DEBIT, end=0, amt=2)  -> sort active_grants -> [[4, 3], [9, 4]]
                                    deduct 2 from b (end=4) -> [[4, 1], [9, 4]]

At query t=4: prune keeps end >= 4 -> [[4, 1], [9, 4]] -> balance = 1 + 4 = 5
At query t=5: prune keeps end >= 5 -> [[9, 4]] (b's leftover 1 expired!) -> balance = 4

Complexity

Let E be the total number of recorded events (grants + debits), and let A (A <= E) be the maximum number of simultaneously active grants during a replay.

  • add_credit and subtract:
    • Time: O(1) average. Checking credit_id in self.used_ids and inserting into a hash set take O(1) average time, and appending a tuple to self.grants or self.debits takes O(1) amortized time.
    • Space: O(E) total across all calls, since we store one small tuple per valid grant or debit plus one ID string per grant in self.used_ids.
  • get_balance(timestamp):
    • Time: O(E log E + E * A log A). Filtering all E events takes O(E), sorting up to E event tuples takes O(E log E), and during replay each event prunes active_grants in O(A) while debit events also sort active_grants in O(A log A). Finally, has_valid_grant scans the grant list once in O(E).
    • Space: O(E). The filtered events list and active_grants list each hold at most E items during the query.

Edge cases

  • Query earlier than every grant (t = 0 when earliest grant starts at t = 1): has_valid_grant(0) is False, so get_balance(0) returns None.
  • Query on the exact expiration timestamp (t == start + expiration): Because validity is a closed interval [start, end], end_time >= current_time keeps the grant active; at t + 1 it expires.
  • Zero-duration grant (expiration == 0): Valid at the single instant [timestamp, timestamp] and expired at timestamp + 1.
  • Zero-amount grant (amount == 0) or completely spent grant: As long as debt == 0 and at least one grant's [start, end] covers timestamp, get_balance(timestamp) returns 0, not None.
  • Rejected add_credit call: Validation runs before self.used_ids.add(credit_id), so a call with amount < 0 or expiration < 0 raises ValueError without reserving credit_id.
  • Debt outliving expired grants: Debt never expires on its own; even long after all grants expire, debt > 0 forces get_balance to return None until future grants repay every unit of debt.

Common mistakes

  • Using < instead of <= on expiration (end_time > current_time): That treats [start, end] as half-open and prematurely drops credits on their final valid timestamp. Keep grants whenever end_time >= current_time.
  • Pruning expired grants only at the end of get_balance: If you forget to prune right before each debit at event_time, a debit at t = 4 will illegally spend credits from a grant that already expired at t = 2.
  • Returning None whenever total_balance == 0: 0 means "a valid grant covers this timestamp, and zero credits remain"; None means either "unpaid debt exists" or "no grant covers this timestamp at all." Be especially careful if you later optimize active_grants into a heap that pops depleted grants — an empty heap can still have 0 balance if a depleted grant's [start, end] window hasn't expired yet!
  • Breaking same-timestamp grant ties by arrival order: Suppose debt = 3 and two grants arrive at t = 5: g1 (3 credits expiring at 6) and g2 (3 credits expiring at 100). Using g1 to repay debt leaves 3 credits until t = 100, whereas using g2 leaves 0 after t = 6. Including end_time in the event sort tuple ensures g1 always pays debt first regardless of arrival order.

Follow-up questions

  • How do we speed up replay from O(E * A log A) to O(E log E)? Replace the active_grants list with a min-heap (heapq — a binary tree stored in an array that pops the smallest [end_time, remaining] in O(log A) time) and use lazy deletion (whenever we process an event at event_time, repeatedly pop the heap top while heap[0][0] < event_time). Each grant is pushed and popped at most once across the entire replay, so all heap operations sum to O(E log A).
  • What if events are guaranteed in chronological order (Parts 1–3 only)? Then we don't need to replay from scratch on each query! We can maintain one persistent min-heap of active grants, one debt integer, and track max_end_time_seen (since timestamps never decrease, max_end_time_seen >= timestamp tells us in O(1) whether any grant covers timestamp), making every operation O(log A) amortized.
  • What if queries are frequent (Q is huge) AND events can still arrive out of order? Keep events in a sorted list (bisect.insort) and save periodic snapshots / checkpoints (deep copies of (debt, heap) every K = sqrt(E) events). A query at timestamp jumps to the latest checkpoint <= timestamp and replays at most K events; an out-of-order historical insert only invalidates checkpoints after its timestamp.
  • How would this look in a production billing service? Store an immutable per-account event log partitioned by account_id, attach an idempotency key (a unique client-generated request ID so network retries never double-charge subtract), and represent currency/GPU-seconds as integer micro-units rather than floating-point numbers to avoid rounding drift.

More OpenAI problems