Escrow-Style Ledger with Expiring Transfers and Account Merging
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate an in-memory ledger with held transfers that expire after a day, account merging, and a ranking of accounts by completed outgoing totals.
You are building a small in-memory ledger and replaying a batch of commands against it. Implement run_bank_ledger(commands, params). It takes two parallel lists, where commands[i] is the name of an operation and params[i] is the list of its arguments. It applies the operations in order, starting from an empty ledger, and returns a list with one result per operation.
Timestamps are integers in milliseconds and are non-decreasing across the batch. Account ids are strings. Amounts are non-negative integers.
Transfers and expiration
A transfer moves money in two steps. When it is created, the money is taken out of the source balance and held. It stays pending until the target accepts it. A transfer created at time t expires once the clock reaches t + 86_400_000. At any timestamp greater than or equal to t + 86_400_000, a still-pending transfer is expired. When a transfer expires, its held amount goes back to the balance of its current source account.
Every operation except create_account must first expire all pending transfers whose deadline has been reached at that operation's timestamp, and only then do its own work.
Operations
Each params[i] has the argument layout shown below, and the result is appended to the output list. null means None.
-
create_accountwith[timestamp, account_id]- If the id is new, create the account with balance
0and outgoing total0, and returntrue. - If the id already exists, change nothing and return
false.
- If the id is new, create the account with balance
-
depositwith[timestamp, account_id, amount]- Add
amountto the account and return the new balance. - Return
nullif the account does not exist.
- Add
-
transferwith[timestamp, source_id, target_id, amount]- Return
nullif either account does not exist, if the two ids are equal, or if the source balance is less thanamount. - Otherwise subtract
amountfrom the source balance immediately, record a pending transfer, and return its id as a string. Ids are"transfer1","transfer2", and so on. The counter advances only when a transfer is successfully created.
- Return
-
accept_transferwith[timestamp, account_id, transfer_id]- Return
trueonly if the transfer exists, is still pending, andaccount_idis its current target. In that case, add the held amount to the target's balance, add it to the source's outgoing total, and mark the transfer accepted. - Otherwise return
false. This covers unknown ids, transfers already accepted, expired, or canceled, and the wrong account.
- Return
-
top_outgoingwith[timestamp, n]- Rank all existing accounts by outgoing total, largest first. Ties are broken by the lexicographically smaller account id.
- Return the ids of the first
naccounts as a list of strings. Ifnis larger than the number of accounts, return all of them. Ifnis0or negative, return an empty list. - Only accepted transfers count toward outgoing totals. Pending and expired transfers do not. Accounts with outgoing total
0are still ranked.
-
merge_accountswith[timestamp, destination_id, source_id]- Return
falseand change nothing if either account does not exist or the two ids are equal. - Otherwise:
- Add the source's balance and outgoing total to the destination's.
- Every pending transfer that goes between the destination and the source, in either direction, is canceled, and its held amount is added to the destination's balance.
- Every other pending transfer whose source or target is the source account is rewritten to use the destination account instead. Its held money stays held, and its original deadline is unchanged.
- Delete the source account.
- Return
true.
- Return
An unknown command name is invalid input and may raise ValueError.
Output
Return a list of results in the same order as the commands. Results are booleans, integers, strings, lists of strings, or None, as described above.
Constraints
len(commands) == len(params).- Timestamps are non-negative integers and never decrease from one operation to the next.
- Amounts are non-negative integers. Zero-amount deposits and transfers are valid.
- Account ids are non-empty strings. Comparison for tie-breaking is standard string ordering.
- Canceled, accepted, and expired transfers can never be accepted later.
- The number of operations is small enough for a straightforward simulation. A scan over all transfers during
merge_accountsis acceptable.
Examples
Example 1
Input: run_bank_ledger(['create_account', 'create_account', 'deposit', 'transfer', 'accept_transfer', 'top_outgoing'], [[1, 'alice'], [2, 'bob'], [3, 'alice', 100], [4, 'alice', 'bob', 40], [5, 'bob', 'transfer1'], [6, 2]])
Output: [True, True, 100, 'transfer1', True, ['alice', 'bob']]
Example 2
Input: run_bank_ledger(['create_account', 'create_account', 'deposit', 'transfer', 'deposit', 'accept_transfer'], [[1, 'a'], [2, 'b'], [3, 'a', 50], [4, 'a', 'b', 20], [86400004, 'b', 5], [86400005, 'b', 'transfer1']])
Output: [True, True, 50, 'transfer1', 5, False]
Hints
Hint 1
Keep, per account, the available balance (held money already subtracted) and the total of accepted outgoing money. Keep each transfer as a record with source, target, amount, deadline and status.
Hint 2
Because timestamps never decrease, you can keep the deadlines in a min-heap and run one expire routine at the start of every operation except account creation. Pop while the smallest deadline is <= the current timestamp, and skip entries whose status is no longer pending.
Hint 3
For merging, move the source's balance and outgoing total into the destination, then walk the pending transfers. Cancel and refund the destination for ones between the two accounts, and rewrite the source id to the destination id in the rest. Refunds on expiry go to the transfer's current source.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a state simulation. The key is a clean data model plus one consistent expiration rule.
State
balances[account]: the available balance. Money held by a pending transfer has already been subtracted.outgoing[account]: the total of accepted outgoing transfers.transfers[id]: a record with source, target, amount and status (pending,accepted,expired,cancelled).- A min-heap of
(deadline, transfer_id).
Expiration. Timestamps never decrease, so once a deadline is reached it stays reached. Before every operation except create_account, pop heap entries with deadline <= timestamp. For each one that is still pending, mark it expired and refund the held amount to its current source. Entries for transfers already accepted or canceled are skipped. This is lazy deletion.
Operations
create_account: reject duplicates, otherwise insert zeros.deposit: expire, then add. A refund from a just-expired transfer is already included in the returned balance.transfer: expire, validate (both accounts exist, ids differ, enough balance), subtract the amount, store the record, push its deadline, and return the next id. The counter advances only on success.accept_transfer: expire, then require that the transfer exists, is pending, and that the caller is its current target. Credit the target and add to the source's outgoing total.top_outgoing: expire, sort by(-outgoing, id), and slice tomax(0, n).merge_accounts: expire, validate, add the source's balance and outgoing total to the destination, then scan pending transfers. Those between the two accounts are canceled and refunded to the destination. Others have source or target rewritten from the source id to the destination id. Finally delete the source.
Why it is correct
- Money is always in exactly one place: an account balance, or the amount of a pending transfer. Each transfer leaves the pending state once (accepted, expired or canceled), and each exit sends its money to exactly one live account.
- Running expiration at the start of every operation makes the observed state equal to one where each expiration happened at its exact deadline, using the rule that
timestamp >= created + 86,400,000means expired. - After a merge every pending transfer references only live accounts, so later refunds and acceptances never touch a deleted account. Canceling transfers between the two merged accounts prevents self-transfers.
- Only acceptance changes
outgoing, so pending and expired transfers never affect rankings.
Complexity
Let A be the number of accounts, T the number of transfers, and Q the number of operations.
- Expiration across the whole run costs O(T log T), since each transfer is pushed and popped at most once.
create_account,depositandaccept_transferare O(1) beyond expiration.transferis O(log T).top_outgoingis O(A log A).merge_accountsis O(T) because it scans the transfers.- Space is O(A + T).
Reference solution
from typing import List
import heapq
def run_bank_ledger(commands: List[str], params: List[List]) -> List[object]:
expiration_ms = 86_400_000
balances = {}
outgoing = {}
transfers = {}
expiry_heap = []
next_id = 1
results = []
def expire(now):
while expiry_heap and expiry_heap[0][0] <= now:
_, tid = heapq.heappop(expiry_heap)
tr = transfers.get(tid)
if tr is not None and tr['status'] == 'pending':
tr['status'] = 'expired'
src = tr['source']
if src in balances:
balances[src] += tr['amount']
for command, args in zip(commands, params):
if command == 'create_account':
timestamp, account_id = args
if account_id in balances:
results.append(False)
else:
balances[account_id] = 0
outgoing[account_id] = 0
results.append(True)
elif command == 'deposit':
timestamp, account_id, amount = args
expire(timestamp)
if account_id not in balances:
results.append(None)
else:
balances[account_id] += amount
results.append(balances[account_id])
elif command == 'top_outgoing':
timestamp, n = args
expire(timestamp)
ordered = sorted(outgoing, key=lambda a: (-outgoing[a], a))
results.append(ordered[:max(0, n)])
elif command == 'transfer':
timestamp, source, target, amount = args
expire(timestamp)
if (source not in balances or target not in balances
or source == target or balances[source] < amount):
results.append(None)
else:
tid = f'transfer{next_id}'
next_id += 1
balances[source] -= amount
transfers[tid] = {
'source': source,
'target': target,
'amount': amount,
'status': 'pending',
}
heapq.heappush(expiry_heap, (timestamp + expiration_ms, tid))
results.append(tid)
elif command == 'accept_transfer':
timestamp, account_id, tid = args
expire(timestamp)
tr = transfers.get(tid)
if tr is None or tr['status'] != 'pending' or tr['target'] != account_id:
results.append(False)
else:
tr['status'] = 'accepted'
balances[account_id] += tr['amount']
outgoing[tr['source']] += tr['amount']
results.append(True)
elif command == 'merge_accounts':
timestamp, dest, src = args
expire(timestamp)
if dest not in balances or src not in balances or dest == src:
results.append(False)
continue
balances[dest] += balances[src]
outgoing[dest] += outgoing[src]
for tr in transfers.values():
if tr['status'] != 'pending':
continue
between = ((tr['source'] == dest and tr['target'] == src)
or (tr['source'] == src and tr['target'] == dest))
if between:
tr['status'] = 'cancelled'
balances[dest] += tr['amount']
continue
if tr['source'] == src:
tr['source'] = dest
if tr['target'] == src:
tr['target'] = dest
del balances[src]
del outgoing[src]
results.append(True)
else:
raise ValueError(f'Unknown operation: {command}')
return results