progress

~/problems / Stateful stores / Bank system

Settle a night's tab all-or-nothing

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

After a climbing club's night out, the treasurer settles up with one batch of transfers: either all of it goes through, or none of it.

Build Ledger with:

  • open(account_id, initial) -> bool: create an account holding initial; False (no change) if the id is taken or initial is negative.
  • balance(account_id) -> int | None: the balance, or None if unknown.
  • settle(transfers) -> int: apply (source, target, amount) tuples in order. Each must be valid when applied, counting earlier transfers in the batch: both accounts exist, source != target, amount is a positive int, and source holds at least amount. If all are valid, apply them and return -1 (also for an empty batch). Otherwise return the index of the first invalid one and change nothing.
L = Ledger()
L.open("ann", 50); L.open("bo", 0); L.open("cy", 10)

L.settle([("ann", "bo", 30), ("bo", "cy", 30)])   # -1: bo received 30 first, so it can pay 30
L.balance("bo"), L.balance("cy")                  # (0, 40)

L.settle([("cy", "ann", 40), ("cy", "bo", 1)])    # 1: cy is empty after the first transfer
L.balance("cy"), L.balance("ann")                 # (40, 20): nothing changed

⭐ Bonus: copying every balance per batch still passes; a speed test with 20,000 small batches on 100,000 accounts earns a star if settle costs only the batch size.

Show hint

keep a small dict of pending balances for the accounts this batch touches; check each transfer against it, and copy it into the real balances only if all pass.

Topic: Bank system. Accounts, transfers that must be accepted, merges; state machines.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc