Command-Driven Ledger with Transfer Volume Leaderboard
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate an in-memory ledger from text commands, with validated transfers and a leaderboard ranked by outgoing volume with an alphabetical tie-break.
Command-Driven Ledger with Transfer Volume Leaderboard
You are building a small in-memory ledger. It receives a list of text commands and must process them in order, producing one output string per command.
Each account has two numbers:
- its current balance, and
- its sent volume, the total of all money it has successfully transferred out so far.
Both start at 0 when the account is created.
Implement run_ledger_commands(commands), which returns a list of strings. Entry i is the response to commands[i]. Tokens in a command are separated by single spaces.
Supported commands
CREATE <account_id>
- If no account with this ID exists, create it with balance
0and sent volume0, and respond"true". - If the ID already exists, change nothing and respond
"false".
DEPOSIT <account_id> <amount>
- If the account exists and
amount > 0, addamountto its balance and respond with the new balance as a decimal string. - If the account does not exist, or
amount <= 0, change nothing and respond with the empty string""(not"false"). - Deposits never change sent volume.
TRANSFER <source_id> <target_id> <amount>
The transfer is valid only if all of these hold:
- both accounts exist,
source_idandtarget_idare different,amount > 0,- the source balance is at least
amount.
If valid, subtract amount from the source balance, add it to the target balance, add amount to the source's sent volume, and respond "true".
If any condition fails, change nothing and respond "false".
TOP_ACTIVITY <k>
- Rank all existing accounts by sent volume, highest first.
- Accounts with equal sent volume are ordered by account ID in ascending lexicographic (character code) order. For example,
"B"comes before"a", and digits come before letters. - Respond with the IDs of the first
kaccounts in that order, joined by commas with no spaces, e.g."ACC1,ACC2". - If there are fewer than
kaccounts, include all of them. - Accounts with zero sent volume still count and appear in the ranking.
- If no accounts exist, respond with the empty string
"".
Constraints
1 <= len(commands) <= 20,000- Account IDs are made of letters and digits (
[a-zA-Z0-9]) and have length1to32. 1 <= amount <= 1,000,000,000for amounts that appear in commands.1 <= k <= 1,000- Balances and volumes fit in a signed 64-bit integer.
- Every command is well formed and uses one of the four names above.
Examples
Example 1
Input: run_ledger_commands(['CREATE A', 'CREATE B', 'CREATE C', 'DEPOSIT A 100', 'DEPOSIT B 50', 'TRANSFER A B 30', 'TRANSFER B C 20', 'TRANSFER A C 10', 'TOP_ACTIVITY 2', 'TRANSFER C A 100', 'TOP_ACTIVITY 3'])
Output: ['true', 'true', 'true', '100', '50', 'true', 'true', 'true', 'A,B', 'false', 'A,B,C']
Example 2
Input: run_ledger_commands(['CREATE Z', 'CREATE A', 'TOP_ACTIVITY 2', 'DEPOSIT Z 5', 'TRANSFER Z A 5', 'TOP_ACTIVITY 2'])
Output: ['true', 'true', 'A,Z', '5', 'true', 'Z,A']
Hints
Hint 1
Keep two hash maps keyed by account ID: one for balances and one for cumulative sent volume. Create both entries together in CREATE so every account can be ranked.
Hint 2
For TRANSFER, compute all validity conditions first (both exist, different accounts, positive amount, enough balance) and only then update the three values, so a failed transfer changes nothing.
Hint 3
For TOP_ACTIVITY, sort account IDs by the pair (-sent_volume, account_id) and slice the first k. Python's default string comparison already gives the required tie-break order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the ledger as a small state machine. Keep two dictionaries keyed by account ID:
balance[id]: the current balance.sent[id]: the cumulative amount successfully transferred out.
Walk through the commands in order, split each into tokens, and handle it by its first token.
- CREATE: if the ID is already in the dictionaries, answer
"false". Otherwise set both values to0and answer"true". Initializing both together means every account can appear in rankings, even with zero volume. - DEPOSIT: if the account is missing or the amount is not positive, answer
"". Otherwise increase the balance and answer with the new balance as a string. Sent volume is untouched. - TRANSFER: evaluate a single boolean covering every rule (both accounts exist, they differ, the amount is positive, the source has enough funds). Only if it is true, apply the three updates: debit the source, credit the target, add to the source's sent volume. Otherwise answer
"false"and leave everything as it was. - TOP_ACTIVITY: sort the account IDs with the key
(-sent[id], id)and take the firstk. Join them with commas. Slicing handlesklarger than the number of accounts, and joining an empty list gives""when no accounts exist.
Why it is correct
- No partial updates. All validation happens before any write, so a rejected transfer cannot leave the state half-changed.
- Self-transfers. The
src != dstcheck matters. Without it, a self-transfer would leave the balance unchanged but still inflate the sent volume. - Non-negative balances. Balances start at 0, deposits add positive amounts, and transfers require
balance >= amountbefore subtracting. A transfer of exactly the full balance is allowed. - Ranking order. Tuples compare element by element. Negating the volume makes larger volumes sort first, and the ID in second place breaks ties in ascending code-point order, which is the required lexicographic order.
Complexity
Let n be the number of accounts.
- CREATE, DEPOSIT and TRANSFER take O(1) average time and O(1) extra space.
- TOP_ACTIVITY takes O(n log n) time for the sort and O(n) extra space. With at most 20,000 commands this is fast enough. Using
heapq.nsmallest(k, ...)would reduce it to O(n log k). - Total storage is O(n).
Reference solution
from typing import List
def run_ledger_commands(commands: List[str]) -> List[str]:
balance = {}
sent = {}
responses = []
for line in commands:
tokens = line.split()
op = tokens[0]
if op == "CREATE":
acc = tokens[1]
if acc in balance:
responses.append("false")
else:
balance[acc] = 0
sent[acc] = 0
responses.append("true")
elif op == "DEPOSIT":
acc = tokens[1]
amount = int(tokens[2])
if acc not in balance or amount <= 0:
responses.append("")
else:
balance[acc] += amount
responses.append(str(balance[acc]))
elif op == "TRANSFER":
src, dst = tokens[1], tokens[2]
amount = int(tokens[3])
ok = (
src in balance
and dst in balance
and src != dst
and amount > 0
and balance[src] >= amount
)
if ok:
balance[src] -= amount
balance[dst] += amount
sent[src] += amount
responses.append("true")
else:
responses.append("false")
elif op == "TOP_ACTIVITY":
k = int(tokens[1])
order = sorted(sent, key=lambda a: (-sent[a], a))
responses.append(",".join(order[:k]))
return responses