Banking Ledger with Time-Based Transfers and Account Consolidation
Data Structure DesignAuto-graded · 13 test casesLast updated
Build an in-memory banking system that processes timed fund transfers deterministically and consolidates accounts with automatic transaction rerouting.
Problem Statement
Build an in-memory banking ledger that handles accounts, delayed fund transfers, and account consolidation. All monetary amounts are non-negative integers representing cents.
Implement a BankingLedger class with these operations:
Operations
create_account(account_id: str, initial_balance: int) -> bool
Opens a new account with the given identifier and starting balance. Returns False if the account identifier is already in use or if the initial balance is negative. Returns True on success.
schedule_payment(payment_id: str, timestamp: int, from_account: str, to_account: str, amount: int) -> bool
Registers a future transfer to be executed when time advances to the specified timestamp. Each payment identifier must be unique across all time—once used, a payment ID cannot be reused even if the payment failed or was cancelled.
Returns False if:
- The payment identifier has been used before
- Either account does not exist
- Both accounts resolve to the same active account
- The amount is zero or negative
Returns True when the payment is successfully registered.
cancel_payment(payment_id: str) -> bool
Cancels a pending payment before it executes. Returns True if the payment was pending and is now cancelled. Returns False if the payment does not exist, has already executed, has already failed, or was already cancelled.
merge_accounts(source_account: str, target_account: str) -> bool
Consolidates the source account into the target account. The source account's entire balance is transferred to the target, and the source account is permanently retired. All future operations involving the retired account will automatically use the target account instead.
If multiple consolidations form a chain (A consolidated into B, then B into C), all references to A or B automatically resolve to C.
Returns False if:
- Either account does not exist
- Both accounts resolve to the same active account
- Source and target are identical
Returns True on success.
advance_time(current_time: int) -> List[dict]
Executes all pending payments with timestamp ≤ current_time in deterministic order:
- Payments with earlier timestamps execute first
- Among payments with the same timestamp, execute in lexicographic order by payment_id (ascending)
For each payment, the system resolves both accounts to their current active accounts, then attempts the transfer:
- If the source account has sufficient balance, the transfer succeeds (status
"SUCCESS") - If the source account has insufficient balance, the payment fails (status
"FAILED") and no money moves
Returns a list of dictionaries in execution order: {"payment_id": str, "status": "SUCCESS" | "FAILED", "timestamp": int} where timestamp is the payment's scheduled time.
get_balance(account_id: str) -> int
Returns the current balance of the account. If the account was consolidated into another account, returns the balance of the active target account. Returns -1 if the account identifier was never created.
Constraints
- Account identifiers and payment identifiers are non-empty strings
- All balances and amounts are non-negative integers (0 ≤ value ≤ 10^9)
- Timestamps are integers (may be negative, zero, or positive)
- At most 10^4 total operations across all method calls
- Account identifiers are at most 20 characters
- Payment identifiers are at most 30 characters
Examples
Example 1
Input: execute_banking_operations(['create_account', 'create_account', 'create_account', 'schedule_payment', 'schedule_payment', 'advance_time', 'merge_accounts', 'get_balance', 'get_balance'], [['acc1', 100], ['acc2', 50], ['acc3', 0], ['p2', 10, 'acc1', 'acc2', 60], ['p1', 10, 'acc1', 'acc3', 50], [10], ['acc3', 'acc2'], ['acc2'], ['acc3']])
Output: [True, True, True, True, True, [{'payment_id': 'p1', 'status': 'SUCCESS', 'timestamp': 10}, {'payment_id': 'p2', 'status': 'FAILED', 'timestamp': 10}], True, 100, 100]
Hints
Hint 1
Use union-find to track account consolidation chains. Each account points to its parent, and roots represent active accounts with meaningful balances.
Hint 2
Store original account identifiers in payment records and resolve them to active accounts only when executing. This automatically handles rerouting through consolidation chains.
Hint 3
When multiple payments have the same timestamp, sort by payment_id to ensure deterministic execution order. Earlier payments in the batch affect the balances available for later payments.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires managing accounts that can be consolidated into one another while ensuring time-based fund transfers execute deterministically. The solution combines two data structures:
Union-Find for Account Consolidation
Track account relationships using a parent pointer map where each account initially points to itself. When one account is consolidated into another, update the parent pointer to create a chain. To find the active account for any identifier, follow parent pointers to the root and apply path compression to flatten the tree for faster future lookups.
Only root accounts maintain meaningful balances. When consolidating, add the source's balance to the target and mark the source as retired by pointing it to the target. Retired accounts can never be recreated.
Lazy Resolution for Payment Rerouting
Store the original account identifiers in each payment record rather than resolving them immediately. When advance_time executes a payment, resolve both endpoints to their current active accounts at that moment. This provides automatic rerouting through arbitrarily long consolidation chains without scanning or updating pending payments when consolidations occur.
Deterministic Execution
When advancing time, collect all pending payments with timestamp ≤ current_time and sort them by (timestamp, payment_id). This total ordering ensures that given the same operations, payments always execute in the same sequence. Execute payments sequentially so that earlier payments affect the balances available for later ones.
Idempotency Registry
The payments dictionary serves as a registry of all payment identifiers ever used. Once registered, a payment ID cannot be reused regardless of outcome (success, failure, or cancellation). This prevents duplicate scheduling and ensures each payment has exactly one execution attempt.
Why It Works
Balance conservation holds because consolidation transfers the full balance from source to target, and successful payments subtract from one root and add the same amount to another. Failed payments move no money.
Automatic rerouting works because only roots hold meaningful balances and payments resolve endpoints at execution time. A payment always operates on the accounts that currently own the funds, regardless of consolidation history.
Determinism follows from the total ordering imposed by sorting on (timestamp, payment_id). Since payment IDs are unique, no two payments compare equal, giving a consistent execution sequence.
Complexity
Let n = number of accounts, P = total payments registered, k = payments due in one advance_time call.
Time Complexity:
_resolve: O(α(n)) amortized with path compression, effectively constantcreate_account,cancel_payment: O(1)schedule_payment,merge_accounts,get_balance: O(α(n)) for one or two resolvesadvance_time: O(P + k log k) to scan all payments and sort the due subset, plus k resolves
Space Complexity: O(n + P) for accounts and payment records
Implementation
from typing import List
class BankingLedger:
def __init__(self):
self.parent = {}
self.balance = {}
self.payments = {}
def _resolve(self, account_id):
if account_id not in self.parent:
return None
root = account_id
while self.parent[root] != root:
root = self.parent[root]
while self.parent[account_id] != account_id:
next_account = self.parent[account_id]
self.parent[account_id] = root
account_id = next_account
return root
def create_account(self, account_id, initial_balance):
if account_id in self.parent or initial_balance < 0:
return False
self.parent[account_id] = account_id
self.balance[account_id] = initial_balance
return True
def schedule_payment(self, payment_id, timestamp, from_account, to_account, amount):
if payment_id in self.payments or amount <= 0:
return False
source = self._resolve(from_account)
target = self._resolve(to_account)
if source is None or target is None or source == target:
return False
self.payments[payment_id] = {
'timestamp': timestamp,
'from': from_account,
'to': to_account,
'amount': amount,
'status': 'PENDING',
}
return True
def cancel_payment(self, payment_id):
payment = self.payments.get(payment_id)
if payment is None or payment['status'] != 'PENDING':
return False
payment['status'] = 'CANCELLED'
return True
def merge_accounts(self, source_account, target_account):
source = self._resolve(source_account)
target = self._resolve(target_account)
if source is None or target is None or source == target:
return False
self.balance[target] += self.balance[source]
self.balance[source] = 0
self.parent[source] = target
return True
def advance_time(self, current_time):
due = sorted(
(payment['timestamp'], payment_id, payment)
for payment_id, payment in self.payments.items()
if payment['status'] == 'PENDING' and payment['timestamp'] <= current_time
)
results = []
for timestamp, payment_id, payment in due:
source = self._resolve(payment['from'])
target = self._resolve(payment['to'])
if self.balance[source] < payment['amount']:
status = 'FAILED'
else:
self.balance[source] -= payment['amount']
self.balance[target] += payment['amount']
status = 'SUCCESS'
payment['status'] = status
results.append({'payment_id': payment_id, 'status': status, 'timestamp': timestamp})
return results
def get_balance(self, account_id):
root = self._resolve(account_id)
return -1 if root is None else self.balance[root]
def execute_banking_operations(operations, arguments):
ledger = BankingLedger()
results = []
for operation, args in zip(operations, arguments):
results.append(getattr(ledger, operation)(*args))
return results