Design an in-memory banking system with transfers and a top spenders ranking
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a simplified banking system that supports creating accounts, depositing money, and transferring funds between accounts. Every operation is associated with a strictly increasing `timestamp` (in milliseconds).
The system should also expose an analytics method that returns the top `n` accounts ranked by total outgoing transaction volume. Outgoing volume is the total `amount` of money that has moved out of an account through successful `transfer` operations. Deposits do not count toward outgoing volume.
All operations must be atomic: if any precondition fails (such as an unknown account, duplicate creation, or insufficient balance), the operation must return `False` (or `None` for queries) and leave the system state unchanged.
Implement a `BankingSystem` class with the following methods:
- `create_account(timestamp: int, account_id: str) -> bool`: Create a new account with the given `account_id` and zero balance. Returns `True` on success, or `False` if the account already exists.
- `deposit(timestamp: int, account_id: str, amount: int) -> Optional[int]`: Deposit `amount` into the account. Returns the new balance, or `None` if the account does not exist.
- `transfer(timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]`: Transfer `amount` from `source_id` to `target_id`. Returns the new balance of the source account on success, or `None` if either account is missing, the source equals the target, or the source has insufficient funds. The transferred amount is added to the source account's outgoing total.
- `top_spenders(timestamp: int, n: int) -> List[str]`: Return the top `n` accounts ranked by total outgoing transfer amount in descending order. Ties are broken by ascending lexicographic `account_id`. Each entry is formatted as `"accountId(outgoing)"`. Every existing account takes part in the ranking, including accounts with no outgoing transfers, which show `0`. If fewer than `n` accounts exist, return all of them.
Example 1:
```text
create_account(1, "alice") -> True
create_account(2, "bob") -> True
create_account(3, "alice") -> False
deposit(4, "alice", 500) -> 500
deposit(5, "carol", 100) -> None
transfer(6, "alice", "bob", 200) -> 300
transfer(7, "bob", "alice", 1000) -> None
transfer(8, "alice", "alice", 10) -> None
top_spenders(9, 2) -> ["alice(200)", "bob(0)"]
```
The second `create_account` for `alice` fails because the account exists, and the deposit to `carol` fails because that account was never created. After the first transfer `alice` holds 300 and `bob` holds 200, so `bob` cannot send 1000, and a transfer from `alice` to `alice` is rejected. Only `alice` has outgoing volume (200), and `bob` still appears with 0.
Example 2:
```text
create_account(1, "acc3") -> True
create_account(2, "acc1") -> True
create_account(3, "acc2") -> True
deposit(4, "acc1", 1000) -> 1000
deposit(5, "acc3", 1000) -> 1000
transfer(6, "acc1", "acc2", 400) -> 600
transfer(7, "acc3", "acc2", 400) -> 600
transfer(8, "acc2", "acc1", 100) -> 700
top_spenders(9, 3) -> ["acc1(400)", "acc3(400)", "acc2(100)"]
top_spenders(10, 5) -> ["acc1(400)", "acc3(400)", "acc2(100)"]
```
`acc1` and `acc3` each sent 400, so the tie is broken by id and `acc1` comes first. `acc2` received 800 but sent only 100, and incoming money does not count. Asking for 5 accounts when only 3 exist returns all 3.
```hint Order of checks
In `transfer`, decide whether the call will succeed before you change any balance. A failure discovered halfway through an update is how money disappears.
```
```hint One sort key
A single tuple key can express "larger total first, then smaller id first" in one sort.
```
### Constraints & Assumptions
- `1 <= timestamp <= 10^9`, and timestamps strictly increase across calls.
- `1 <= amount <= 10^9`.
- `account_id` is a non-empty string of alphanumeric characters.
- At most `10^4` operations are performed.
### Clarifying Questions to Ask
- Do timestamps change any result at this stage, or are they there for features added later, such as scheduled payments?
- Are amounts whole units (for example cents), so integer arithmetic is exact? How large can a balance grow?
- Will more operations be added in later stages, and should the class be easy to extend?
- Is the system called from one thread, or must atomicity hold under concurrent calls?
### What a Strong Answer Covers
- The per-account state, and why it makes account creation, deposits and transfers constant time.
- The validation order in `transfer`, so that every failure path leaves balances and outgoing totals unchanged.
- The ranking rule: descending outgoing total, ascending id on ties, zero-volume accounts included, and the exact output format.
- Edge cases such as duplicate creation, unknown accounts, self-transfer, a transfer of the full balance, and `n` larger than the number of accounts.
- Time and space complexity of each method, and how the design leaves room for timestamp-based features.
### Follow-up Questions
- If `top_spenders` is called far more often than `transfer`, how would you avoid a full sort on every call?
- How would you add scheduled payments that execute at a later timestamp, and when would you process them?
- How would you merge two accounts into one, including their balances and outgoing totals?
- How would you keep transfers atomic if several threads call the system at once?
Overview: Implement an in-memory banking system class that creates accounts, takes deposits, moves money between accounts, and ranks accounts by the total they have sent out. It tests atomic validation, simple state design, deterministic tie-breaking in a sort, and planning for features added in later stages.