KatInterview

Expiring Credit Wallet: Drain Soonest-Expiring First, Halt on Overdraft

Data Structure DesignModel answer
MediumModel answerData Structure Designheapgreedysimulation

Last updated

Design an in-memory credit ledger that consumes the earliest-expiring balance first and permanently returns None after any overdraft.

Expiring Credit Wallet

You are building an in-memory wallet for a single account that holds credits with expiration dates. Credits are granted in named buckets, each with an amount and a deadline. Charges are paid out of those buckets according to two firm rules:

Rule 1 — Spend what expires soonest. When a charge arrives, deduct from the bucket with the nearest expiration first. Once that bucket hits zero, continue into the next-soonest bucket, and so on, until the charge is fully covered.

Rule 2 — Overdraft is permanent and fatal. If any charge cannot be fully covered by unexpired credits, the wallet enters a broken state. Every subsequent get_balance call returns None, regardless of any credits added later.

Implement the following interface. All timestamps and amounts are non-negative integers.

class CreditWallet:
    def add_credit(self, amount: int, timestamp: int, expires_at: int) -> None:
        """Add `amount` credits granted at `timestamp`, valid until `expires_at`."""

    def spend_credit(self, amount: int, timestamp: int) -> None:
        """Deduct `amount` credits at `timestamp`."""

    def get_balance(self, timestamp: int) -> int | None:
        """Return total unexpired, unspent credits at `timestamp`, or None if broken."""

Worked example

Operations arrive in the order listed. Timestamps are spaced far enough apart that boundary edge cases do not affect the results.

CallWhat happens
add_credit(10, 0, 5)Bucket A: 10 credits, expires at t=5
add_credit(10, 0, 100)Bucket B: 10 credits, expires at t=100
spend_credit(10, 1)Drains A completely (A expires first)
get_balance(10)Returns 10 — A is expired and empty; B is intact
spend_credit(15, 20)Only 10 credits available; wallet breaks
get_balance(30)Returns None

If the charge at t=1 had been taken from B instead, A would have expired unused and get_balance(10) would return 0 — so the consumption order is the whole point.

Questions to settle before coding

Before you start, think through (and state) your conventions for:

  • Is a credit still usable at exactly its expires_at timestamp, or has it already expired?
  • Can calls arrive out of order, or are timestamps always non-decreasing?
  • If a grant and a charge share the same timestamp, can that grant cover that charge?
  • When the wallet breaks, does None apply to every future query, or only to queries whose timestamp is at or after the overdrafting charge?
  • How should invalid inputs be handled (e.g., negative amount, expires_at ≤ timestamp)?

Part 1 — Implement the wallet

Write a working implementation of the three methods. State the time complexity of each.

Your answer should demonstrate:

  • Correct multi-bucket drainage in a single charge.
  • Expired credits excluded both from get_balance and from covering charges.
  • A broken state that persists unconditionally.
  • Your chosen conventions, stated clearly.

Part 2 — Scaling to very high transaction volume

Suppose one account accumulates millions of grants and charges over its lifetime. How would you evolve the design?

Before answering, consider:

  • Is the pressure many accounts with sparse activity, or a few accounts with dense activity?
  • Must you still answer balance queries for arbitrary past timestamps?

Your answer should address:

  • Where the Part 1 design accumulates unbounded state and what bounds it.
  • How to serve historical or out-of-order queries without replaying the full log every time.
  • What changes if the wallet must survive process restarts, handle duplicate requests, or spread across multiple nodes.

Hints

Hint 1

A min-heap keyed on expiration time gives you O(log n) access to the soonest-expiring bucket — you can pop and partially drain buckets in one pass through the heap during a charge.

Hint 2

Set a simple boolean flag the moment an overdraft occurs; every get_balance check reads that flag first, before touching any bucket or doing any expiry filtering.

Hint 3

For Part 2, think about what 'compacting' means for a ledger: a periodic snapshot of the remaining bucket state lets you discard all history before that point, so you only replay a bounded suffix of events for any query.