Skip to main content
hard

GPU Credits Manager

GPU Credits Manager You're building a GPU credit ledger. Events can arrive out of order. RULES: 1) Grants are valid in [grant_timestamp, expiration_timestamp) 2) subtract() allocates from soonest-expiring grants first (FEFO) - tie-breaker: lexicographically smaller grant_id 3) Overdraw: partial take, no error, no negative balance 4) Timestamps are NOT monotonic 5) Same timestamp: a grant at time T is available for a subtract at time T 6) Duplicate grant_id: ignore the second create_grant (first wins)

Build a GPU credit ledger where events arrive out-of-order. Grants expire, subtracts allocate FEFO (soonest-expiring-first), and queries ask for balance at any timestamp. Part 2 adds retroactive cancellations, forcing full replay correctness.

Examples

You write

CreditsManager: create_grant(timestamp: int, grant_id: str, amount: int, expiration_timestamp: int), subtract(timestamp: int, amount: int), get_balance(timestamp: int)

  1. Example 1

    Input
    Killer: expired grants must still absorb earlier subtracts; create A(10,exp50), B(10,exp100), subtract(40,8), getBalance(50)→10
    returns
    [12, 10, 7, 0]
  2. Example 2

    Input
    Out-of-order + overdraw: subtract(10,8) arrives before grant; later subtract(15,20) overdraws to 0
    returns
    [0, 10, 2, 0]

The pattern behind it

Design

I reach for it when

  • The statement describes a class with methods, not one function.
  • Each method needs to be fast, and the structure decides how fast.

Say this before you type. Say each method, the cost you want from it, and the structure that earns that cost.

All 27 Design problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Replay + FEFOhard
2Part 2

Each locked part opens in the editor once the part before it passes.