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 holdinginitial;False(no change) if the id is taken orinitialis negative.balance(account_id) -> int | None: the balance, orNoneif 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,amountis a positive int, andsourceholds at leastamount. 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.