Account Ledger with Reservation Expiry and Merging
Data Structure DesignModel answerLast updated
Design a banking ledger that supports deposits, time-limited transfer reservations, acceptance of reserved transfers, and merging accounts with their pending operations.
Problem
Design a ledger system for managing accounts with the following capabilities:
Operations:
-
create_account(account_id): Initialize a new account starting at zero balance. ReturnTrueon success,Falseif that ID is already taken or was previously deleted. -
deposit(account_id, amount): Add funds to an existing account. Return the updated balance, orNoneif the account doesn't exist. -
request_transfer(from_id, to_id, amount, timestamp): Reserve funds for a future transfer. The sender must exist, have sufficient available balance (actual balance minus already-reserved amounts), and the recipient must exist. The reservation remains valid for 1000 time units; if not accepted bytimestamp + 1000, it expires automatically. Return a unique reservation ID on success,Noneon failure. -
accept_transfer(reservation_id, current_timestamp): Finalize a reserved transfer. Deduct the amount from the sender, credit the recipient, and consume the reservation. ReturnTrueif successful,Falseif the reservation doesn't exist, has expired (current_timestamp > creation_timestamp + 1000), or was already used. -
merge_accounts(account_id1, account_id2): Consolidateaccount_id2intoaccount_id1. Transfer all funds and migrate all pending outgoing reservations. After merging,account_id2is permanently deleted and cannot be recreated. ReturnTrueon success,Falseif either account is missing or if they're the same.
Rules:
- All amounts and account IDs are positive integers.
- Reservation IDs must be unique across the system's lifetime.
- A reservation accepted at exactly
timestamp + 1000is still valid. - Self-transfers (sender equals recipient) should be rejected.
- After a merge, old reservations referencing the deleted account should resolve to the surviving account.
Example:
ledger = AccountLedger()
ledger.create_account(1) # True
ledger.deposit(1, 100) # 100
ledger.request_transfer(1, 2, 50, 100) # None (account 2 missing)
ledger.create_account(2) # True
res = ledger.request_transfer(1, 2, 50, 100) # returns reservation ID
ledger.accept_transfer(res, 500) # True; balances: 1→50, 2→50
Hints
Hint 1
Track available balance separately from total balance by subtracting active reservation amounts.
Hint 2
Use path compression to resolve merged accounts efficiently when processing reservations.
Hint 3
Clean up expired reservations lazily when checking available balance or processing acceptance.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution
Approach
This problem requires careful state management across five interconnected concerns:
1. Account balances: Store the actual funds for each live account.
2. Reservation tracking: Maintain a registry of pending transfers with their parameters (sender, recipient, amount, creation time).
3. Available balance calculation: An account's spendable balance equals its total minus the sum of all unexpired outgoing reservations. This prevents double-spending when multiple transfers are requested before any are accepted.
4. Account aliasing after merges: When account B is merged into account A, track that B now resolves to A. This ensures old reservations naming B will correctly credit or debit A. Use union-find with path compression for efficient resolution through chains of merges.
5. Lazy expiry: Don't actively scan for expired reservations. Instead, filter them out when calculating available balance or when attempting acceptance. Once identified as expired, delete them immediately.
Data Structures
class AccountLedger:
EXPIRY_WINDOW = 1000
def __init__(self):
self.balances = {} # account_id -> current balance
self.defunct = set() # IDs that were merged away
self.alias_map = {} # merged_id -> surviving_id (union-find parent)
self.reservation_data = {} # res_id -> (from, to, amt, ts)
self.outgoing_holds = {} # account_id -> set of reservation IDs
self.next_res_id = 1
Core Logic
Available balance: Sum all non-expired reservations from an account and subtract from its balance. As we scan, purge any expired entries:
def _compute_available(self, account_id, now):
held = 0
holds = self.outgoing_holds[account_id]
for res_id in list(holds):
amt, created_at = self.reservation_data[res_id][2:4]
if now > created_at + self.EXPIRY_WINDOW:
holds.discard(res_id)
del self.reservation_data[res_id]
else:
held += amt
return self.balances[account_id] - held
Account resolution: Follow the alias chain with path compression to find the current active account for any ID:
def _resolve_account(self, account_id):
root = account_id
while root in self.alias_map:
root = self.alias_map[root]
# Path compression
while account_id in self.alias_map and self.alias_map[account_id] != root:
next_hop = self.alias_map[account_id]
self.alias_map[account_id] = root
account_id = next_hop
return root
Request transfer: Check both accounts exist, verify available funds, create a unique reservation:
def request_transfer(self, from_id, to_id, amount, timestamp):
if from_id not in self.balances or to_id not in self.balances:
return None
if from_id == to_id:
return None
if self._compute_available(from_id, timestamp) < amount:
return None
res_id = self.next_res_id
self.next_res_id += 1
self.reservation_data[res_id] = (from_id, to_id, amount, timestamp)
self.outgoing_holds[from_id].add(res_id)
return res_id
Accept transfer: Resolve both parties, check expiry, move funds only if they're distinct accounts:
def accept_transfer(self, reservation_id, current_timestamp):
if reservation_id not in self.reservation_data:
return False
from_id, to_id, amount, created_at = self.reservation_data[reservation_id]
sender = self._resolve_account(from_id)
receiver = self._resolve_account(to_id)
# Always consume the reservation
del self.reservation_data[reservation_id]
self.outgoing_holds[sender].discard(reservation_id)
if current_timestamp > created_at + self.EXPIRY_WINDOW:
return False
if sender != receiver:
self.balances[sender] -= amount
self.balances[receiver] += amount
return True
Merge accounts: Transfer balance and pending holds, then mark the absorbed account as defunct:
def merge_accounts(self, account_id1, account_id2):
if account_id1 == account_id2:
return False
if account_id1 not in self.balances or account_id2 not in self.balances:
return False
self.balances[account_id1] += self.balances.pop(account_id2)
# Merge hold sets (small-into-large optimization)
holds1 = self.outgoing_holds[account_id1]
holds2 = self.outgoing_holds.pop(account_id2)
if len(holds1) < len(holds2):
holds1, holds2 = holds2, holds1
holds1.update(holds2)
self.outgoing_holds[account_id1] = holds1
self.alias_map[account_id2] = account_id1
self.defunct.add(account_id2)
return True
Complexity
- create_account, deposit: O(1)
- request_transfer: O(P) where P is the number of pending reservations from the sender, with each expired reservation cleaned once
- accept_transfer: O(α(n)) amortized for union-find path compression, nearly constant
- merge_accounts: O(min(H₁, H₂)) for merging hold sets, O(M log M) total across all merges using small-into-large
- Space: O(A + R) for A accounts and R active reservations
Edge Cases
- Missing recipient during request: Return
None - Self-transfer: Rejected at request time
- Double acceptance: Second call returns
Falsesince reservation was consumed - Boundary acceptance: At exactly
timestamp + 1000succeeds; one unit later fails - Insufficient available balance: Multiple overlapping reservations correctly reduce available funds
- Merge into self or nonexistent account: Returns
False - Chained merges: Account C merged into B, then B into A; old reservations for C correctly resolve to A
- Merged account transfer: When both parties resolve to the same account after merging, funds don't actually move but the reservation is successfully consumed
Common Mistakes
- Checking total balance instead of available balance when creating reservations, allowing overdraft
- Not handling expiry at the exact boundary correctly (off-by-one errors)
- Forgetting to remove reservations from the pending set when they expire or are accepted
- Not using path compression in the alias resolution, leading to O(n) lookups through merge chains
- Invalidating reservations after a merge instead of migrating them to the surviving account