In-Memory Bank With Delayed Payments, Cancellation and Spend Ranking
Data Structure DesignModel answerLast updated
Extend an in-memory bank with delayed payments that can be canceled, record success or failure for each, discard stale entries, and rank accounts by total outgoing money.
Delayed Payments in an In-Memory Bank
You are building a single-process, in-memory banking class. Every public method takes a timestamp as its first argument, and timestamps strictly increase from one call to the next. Accounts already support creation, deposits and transfers between accounts. Your job is to add scheduled payments.
Requirements
- Scheduling.
schedule_payment(timestamp, account_id, amount, delay)queues a withdrawal that executes attimestamp + delay.- It returns a unique identifier (
"payment1","payment2", ...), orNoneif the account does not exist. - Persist the result of every payment, whether it succeeded or failed, together with a reason for failure and the time it was processed.
- It returns a unique identifier (
- Execution order. At any given timestamp, all payments that have come due are executed before the current operation does its own work. Payments due at the same moment run in the order they were created.
- A payment succeeds if the balance covers it. Otherwise it fails and nothing changes (no balance change, no effect on outgoing totals).
- Cancellation.
cancel_payment(timestamp, account_id, payment_id)returnsTrueonly if the payment exists, belongs to that account, and has not yet been executed or canceled. Otherwise it returnsFalse. - Cleanup. Canceled payments must not run later, and they should not accumulate in your pending-work structure indefinitely. Results of executed payments must remain queryable.
- Outgoing report.
top_spenders(timestamp, n)returns up tonentries formatted as"account_id(total)", wheretotalis the money that has left the account (outgoing transfers plus successful payments).- Sort by total descending, then by account id ascending.
- Accounts with no outgoing money still count with a total of 0.
What to deliver
Describe your data model and assumptions, explain how you handle due payments, cancellation and cleanup, give the code, and state the time complexity of each operation. Mention how you would test it and how the design might change if it had to scale beyond one process.
Hints
Hint 1
Keep two separate things: a persistent record of every payment with its status, and a work queue holding only what still needs to run. Which structure keeps the queue ordered by due time and creation order?
Hint 2
Removing an arbitrary item from a heap is expensive. Consider just marking a payment as canceled and skipping it when it reaches the top of the queue, then rebuilding the queue when too many dead entries pile up.
Hint 3
Call the same 'process everything due up to this timestamp' routine at the start of every public method, and again after enqueueing a payment with delay 0, so the ordering rules hold without background threads.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Although this is framed as design, it is an implementation task with exact expected outputs. The answer should have a clear data model, deterministic timing semantics and clean code.
Assumptions
- Timestamps strictly increase across calls.
- Payments become due at
timestamp + delay. A due payment runs before the operation that triggered the check. - Ties on due time are broken by creation order.
- A failed payment leaves balances and outgoing totals untouched, and records a reason such as
INSUFFICIENT_FUNDS. cancel_paymentis true only for an existing, matching-account, still-pending payment.- The report sorts by total descending, then id ascending.
Data model
| Structure | Purpose |
|---|---|
balances | Current balance per account |
outgoing | Cumulative money that left each account |
payments | Every payment with status (PENDING, SUCCEEDED, FAILED, CANCELED), reason and processed time |
heap | Min-heap of (due_time, seq, payment_id) for pending work |
The payments dict is the permanent result log. The heap is only a work queue. Separating them is what makes cancellation and cleanup simple.
Key decisions
Lazy, event-driven processing. Every public method begins by popping heap entries whose due time is at most the current timestamp and settling each one. No threads or timers are needed, and the behavior is fully deterministic, which matters for exact-match tests.
Cancellation by lazy deletion. Deleting from the middle of a heap is O(P). Instead, flip the status to CANCELED in O(1). When the processor pops that entry, it sees the payment is no longer pending and skips it.
Cleanup. Canceled entries still occupy heap space. Count them, and when they exceed half the heap, rebuild the heap from pending entries only and heapify (O(P)). Each rebuild is paid for by the cancellations that triggered it, so the amortized cost stays logarithmic. Settled payments leave the heap but remain in payments.
Zero delay. After pushing a payment, run the processor again so a payment with delay == 0 executes immediately.
Report. Build (-total, id) for each account and take the smallest n, or just sort. Format each as id(total).
Code
import heapq
from dataclasses import dataclass
from typing import Optional
@dataclass
class Payment:
payment_id: str
account_id: str
amount: int
exec_time: int
status: str = "PENDING"
reason: Optional[str] = None
processed_at: Optional[int] = None
class BankingSystem:
def __init__(self):
self.balances = {}
self.outgoing = {}
self.payments = {}
self.heap = []
self.seq = 0
self.dead = 0 # canceled entries still in heap
def _process_due(self, ts):
while self.heap and self.heap[0][0] <= ts:
t, _, pid = heapq.heappop(self.heap)
p = self.payments[pid]
if p.status != "PENDING":
self.dead -= 1
continue
p.processed_at = t
if self.balances.get(p.account_id, -1) < 0:
p.status, p.reason = "FAILED", "ACCOUNT_NOT_FOUND"
elif self.balances[p.account_id] < p.amount:
p.status, p.reason = "FAILED", "INSUFFICIENT_FUNDS"
else:
self.balances[p.account_id] -= p.amount
self.outgoing[p.account_id] += p.amount
p.status = "SUCCEEDED"
def _compact(self):
if self.dead * 2 > len(self.heap):
self.heap = [e for e in self.heap
if self.payments[e[2]].status == "PENDING"]
heapq.heapify(self.heap)
self.dead = 0
def schedule_payment(self, ts, account_id, amount, delay):
self._process_due(ts)
if account_id not in self.balances:
return None
self.seq += 1
pid = f"payment{self.seq}"
self.payments[pid] = Payment(pid, account_id, amount, ts + delay)
heapq.heappush(self.heap, (ts + delay, self.seq, pid))
self._process_due(ts)
return pid
def cancel_payment(self, ts, account_id, payment_id):
self._process_due(ts)
p = self.payments.get(payment_id)
if p is None or p.account_id != account_id or p.status != "PENDING":
return False
p.status = "CANCELED"
self.dead += 1
self._compact()
return True
def top_spenders(self, ts, n):
self._process_due(ts)
ranked = sorted(self.outgoing.items(), key=lambda kv: (-kv[1], kv[0]))
return [f"{a}({t})" for a, t in ranked[:n]]
Account creation, deposit and transfer follow the same pattern: call _process_due(ts) first, validate, then mutate. A transfer must also add the amount to the source's outgoing.
Complexity
- Schedule: O(log P) plus settlement work, which is amortized across payments.
- Cancel: O(1), plus amortized O(log P) from compaction.
- Report: O(A log A), or O(A log n) with
heapq.nsmallest. - Memory: O(A + total payments), since the result log is kept.
Common mistakes
- Running the current operation before due payments, which breaks balance checks.
- Removing from the middle of the heap, giving O(P) cancels.
- Letting a failed payment change
outgoing. - Allowing cancel on an already executed payment or one owned by another account.
- Forgetting to execute zero-delay payments immediately.
- Ranking ties by insertion order instead of account id.
- Dropping executed payments so their results can no longer be queried.
Testing
Cover: a payment that succeeds exactly at its due time; two payments due together running in creation order; a deposit that arrives just before a payment is due; cancel before, at and after the due time; cancel with the wrong account; many cancels triggering compaction; and report ties.
Scaling beyond one process
Replace the heap with a durable, partitioned delay queue, for example a table indexed by due time that workers poll. Make execution idempotent by keying on the payment id and using a conditional status update from PENDING. Shard by account so balance checks and debits happen in one transaction, and keep an append-only ledger for auditability.