Account Ledger and Top-Activity Leaderboard
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Implement an in-memory ledger that maintains per-account funds alongside a ranked leaderboard of cumulative transaction volume. Each account tracks two non-negative integers:
- Balance: the funds currently available in the account.
- Activity: the lifetime total of money deposited into the account plus money transferred either out of or into the account across all completed operations.
Support four operations on a BankingSystem instance, exposed through the batch runner banking_system(operations, arguments) which executes operations[i] with argument list arguments[i] on a fresh system and returns a list of results:
def banking_system(operations: List[str], arguments: List[List]) -> List:
create_account(account_id: str) -> bool— Registersaccount_idstarting at0balance and0activity and returnsTrue. Ifaccount_idis already registered, leaves the existing account unchanged and returnsFalse.deposit(account_id: str, amount: int) -> bool— Creditsamounttoaccount_id's balance and increases its activity byamount, returningTrue. ReturnsFalsewithout modifying state ifaccount_iddoes not exist (oramount <= 0).transfer(from_id: str, to_id: str, amount: int) -> bool— Movesamountfromfrom_idtoto_idonly when both accounts exist,from_id != to_id,amount > 0, andfrom_id's current balance is at leastamount. On success,from_id's balance decreases byamount,to_id's balance increases byamount, both accounts' activity totals increase byamount, and the call returnsTrue. Otherwise no balances or activity totals change and the call returnsFalse.get_top_accounts(n: int) -> List[str]— Returns up tonaccount IDs ordered from highest activity to lowest. Break ties between equal activity totals byaccount_idin ascending lexicographical (ASCII string) order. Return all existing accounts when fewer thannexist, and[]whenn <= 0or no accounts exist.
Examples
Example 1
Input:
operations = ["create_account", "create_account", "create_account", "deposit", "transfer", "get_top_accounts"]
arguments = [["vault"], ["checking"], ["savings"], ["vault", 300], ["vault", "checking", 120], [3]]
Output:
[True, True, True, True, True, ["vault", "checking", "savings"]]
"vault" receives a 300 deposit (balance 300, activity 300) and then sends 120 to "checking". That transfer leaves "vault" at balance 180 and activity 300 + 120 = 420, puts "checking" at balance 120 and activity 120, and leaves "savings" at 0, yielding ["vault", "checking", "savings"].
Example 2
Input:
operations = ["create_account", "create_account", "create_account", "deposit", "deposit", "transfer", "get_top_accounts"]
arguments = [["u2"], ["u10"], ["u1"], ["u2", 80], ["u10", 80], ["u2", "u1", 100], [2]]
Output:
[True, True, True, True, True, False, ["u10", "u2"]]
"u2" and "u10" each deposit 80. Attempting to send 100 from "u2" to "u1" fails because "u2" only holds 80, so all balances and activities stay unchanged. For the top 2 accounts, "u10" and "u2" tie at activity 80, and "u10" precedes "u2" in ASCII string order because '1' < '2'.
Constraints
- Every
account_idis a non-empty string. amount >= 1for valid deposits and transfers.- At most
10^5accounts are created (N <= 10^5), and total operations are at most10^5. get_top_accounts(n)must run asymptotically faster than sorting allNaccounts from scratch on each query.
Step-by-step walkthrough
Understand the account rules and leaderboard order
We need to build an in-memory
BankingSystemthat tracks two numbers for each account:balance: how much money the account currently holds (starts at0).activity: the cumulative sum of all successful deposits into the account plus all successful transfers either sent from or received by the account (starts at0).
Four methods operate on the bank, and the automated judge calls them through
banking_system(operations, arguments):create_account(account_id)— creates the account at0balance and0activity, or returnsFalseifaccount_idalready exists (leaving the existing account untouched).deposit(account_id, amount)— addsamountto bothbalanceandactivity, or returnsFalseif the account is missing.transfer(from_id, to_id, amount)— checks that both accounts exist andbalance[from_id] >= amount; if so, movesamountfromfrom_idtoto_idand addsamountto both accounts'activity.get_top_accounts(n)— returns up tonaccount IDs ordered by highestactivityfirst, breaking ties byaccount_idin ascending lexicographical order (standard dictionary/ASCII order, where"A" < "B"and"acc10" < "acc2").
We also enforce two sensible defensive guards: failed operations never partially modify state, and
transferrejects self-transfers (from_id == to_id) and non-positive amounts (amount <= 0) so no account can inflate its activity without moving real funds.Why sorting on every query is too slow
With two dictionaries (
_balanceand_activity),create_account,deposit, andtransfereach take O(1) time. The naive way to answerget_top_accounts(n)is to build[(-activity, account_id) ...]across all N accounts and call.sort()on every query.With up to
N = 10^5accounts, sorting every account on each query costs O(N log N) time even whenn = 3—and the problem explicitly requiresget_top_accountsto beat a full sort on every call. Keeping a Pythonlistsorted withbisectdoes not fix the bottleneck either, becauselist.insertanddelstill shift up to N elements in O(N) time per update.Key idea: a min-heap of (-activity, id) with lazy deletion
Python's
heapqmodule provides a min-heap—a binary tree stored in a list that always keeps the smallest item at index0and supports push and pop in O(log N) time. By storing tuples of(-activity, account_id), Python's tuple comparison gives us the exact leaderboard order we want:- Larger
activityproduces a more negative-activity, so the most active account pops first. - Equal
activityties on-activityand falls back to comparingaccount_idin ascending string order!
A heap cannot cheaply delete an old tuple sitting in the middle when an account's activity grows. Instead, we use lazy deletion:
Account "vault" starts at 0, then deposits 300: _activity = {"vault": 300, "checking": 0} _heap = [ (-300, "vault"), (0, "checking"), (0, "vault") ] ▲ ▲ ▲ LIVE LIVE STALE (300 == 300) (0 == 0) (0 != 300)- On update: update
self._activity[account_id]and push a brand-new(-new_activity, account_id)tuple ontoself._heap, leaving the older tuple behind. - Why staleness is unambiguous: because every deposit and transfer adds
amount > 0, an account's activity strictly increases on every update. Thus each account has exactly one heap tuple matchingself._activity[account_id]; every older tuple has a smaller activity and is skipped when popped. - Keep memory bounded: if many updates happen between queries, stale tuples could pile up. Whenever
len(self._heap) > 2 * len(self._activity), we rebuild the heap fromself._activityin O(N) time usingheapq.heapify. Because at least N pushes must occur before the next rebuild, the rebuild adds only O(1) amortized (averaged over operations) work per push and keeps heap size ≤ 2N.
- Larger
Implement account creation, deposits, and transfers
Let's write
BankingSystem.__init__and the three state-changing methods first. Notice howcreate_accountpushes(0, account_id)right away so brand-new accounts with0activity still appear inget_top_accounts, andtransfervalidates every condition before mutating either account:class BankingSystem: def __init__(self) -> None: # _balance: maps account_id -> current balance, e.g. {"A": 50, "B": 50}. self._balance: Dict[str, int] = {} # _activity: maps account_id -> total successful deposit + transfer volume, e.g. {"A": 150}. self._activity: Dict[str, int] = {} # _heap: min-heap of (-activity, account_id) tuples, e.g. [(-150, "A"), (-50, "B")]. # Negating activity puts the largest activity first, while keeping account_id positive # breaks ties in ascending lexicographical order automatically. self._heap: List[Tuple[int, str]] = [] def create_account(self, account_id: str) -> bool: if account_id in self._balance: return False self._balance[account_id] = 0 self._activity[account_id] = 0 # Insert the 0-activity account immediately so it can appear in get_top_accounts. self._push_ranking(account_id) return True def deposit(self, account_id: str, amount: int) -> bool: # Requiring amount > 0 ensures every update strictly increases activity, # which guarantees older heap entries for the same account become uniquely stale. if amount <= 0 or account_id not in self._balance: return False self._balance[account_id] += amount self._add_activity(account_id, amount) return True def transfer(self, from_id: str, to_id: str, amount: int) -> bool: # Validate every rule up front so failed transfers leave balances and activity untouched. # Rejecting from_id == to_id prevents an account from inflating activity without moving funds. if amount <= 0 or from_id == to_id: return False if from_id not in self._balance or to_id not in self._balance: return False # Strict '<' allows transferring the exact full balance (leaving 0) while blocking overdrafts. if self._balance[from_id] < amount: return False self._balance[from_id] -= amount self._balance[to_id] += amount # Both sender and receiver gain activity on a successful transfer. self._add_activity(from_id, amount) self._add_activity(to_id, amount) return TrueImplement lazy-heap updates and top-n queries
In
get_top_accounts(n), we pop tuples fromself._heapuntil we have collectednlive entries (or the heap runs out). Any stale entry we pop is discarded permanently; the live entries we keep must be pushed back intoself._heapbefore returning so future queries still see them!def get_top_accounts(self, n: int) -> List[str]: # Phase 1: pop up to n live entries, permanently discarding any stale entries we pass. top_entries: List[Tuple[int, str]] = [] while self._heap and len(top_entries) < n: entry = heapq.heappop(self._heap) neg_activity, account_id = entry # An entry is stale if the account's activity has grown since this tuple was pushed. if -neg_activity != self._activity[account_id]: continue top_entries.append(entry) # Phase 2: push the live entries back so reading the leaderboard never mutates it. result: List[str] = [] for entry in top_entries: heapq.heappush(self._heap, entry) result.append(entry[1]) return result def _add_activity(self, account_id: str, amount: int) -> None: self._activity[account_id] += amount self._push_ranking(account_id) def _push_ranking(self, account_id: str) -> None: heapq.heappush(self._heap, (-self._activity[account_id], account_id)) # Once stale entries outnumber live accounts, rebuild in O(N) to bound heap size to <= 2N. if len(self._heap) > 2 * len(self._activity): self._rebuild_ranking() def _rebuild_ranking(self) -> None: self._heap = [] for account_id, activity in self._activity.items(): self._heap.append((-activity, account_id)) heapq.heapify(self._heap)Finally,
banking_system(operations, arguments)instantiates oneBankingSystemand dispatches each operation name to its method.Trace Example 1 step by step
Let's trace Example 1 (
[STALE]marks an outdated heap tuple):Call _balance _activity _heap tuples (ordered view) ─────────────────────────────────── ───────────────────────────── ───────────────────────────── ──────────────────────────────────────────── 1. create_account("vault") {vault:0} {vault:0} [(0,vault)] -> True 2. create_account("checking") {vault:0, checking:0} {vault:0, checking:0} [(0,checking), (0,vault)] -> True 3. create_account("savings") {vault:0, checking:0, {vault:0, checking:0, [(0,checking), (0,savings), (0,vault)] savings:0} savings:0} -> True 4. deposit("vault", 300) {vault:300, checking:0, {vault:300, checking:0, [(-300,vault), (0,checking), (0,savings), savings:0} savings:0} (0,vault)[STALE]] -> True 5. transfer("vault","checking",120) {vault:180, checking:120, {vault:420, checking:120, [(-420,vault), (-300,vault)[STALE], savings:0} savings:0} (-120,checking), (0,checking)[STALE], (0,savings), (0,vault)[STALE]] -> True 6. get_top_accounts(3) unchanged unchanged pops (-420,vault) [keep], discards (-300,vault) [stale], pops (-120,checking) [keep], discards (0,checking) [stale], pops (0,savings) [keep], pushes 3 live back -> ["vault", "checking", "savings"]The returned list is
[True, True, True, True, True, ["vault", "checking", "savings"]], matching Example 1.Full solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq class BankingSystem: def __init__(self) -> None: # _balance: maps account_id -> current balance, e.g. {"A": 50, "B": 50}. self._balance: Dict[str, int] = {} # _activity: maps account_id -> total successful deposit + transfer volume, e.g. {"A": 150}. self._activity: Dict[str, int] = {} # _heap: min-heap of (-activity, account_id) tuples, e.g. [(-150, "A"), (-50, "B")]. # Negating activity puts the largest activity first, while keeping account_id positive # breaks ties in ascending lexicographical order automatically. self._heap: List[Tuple[int, str]] = [] def create_account(self, account_id: str) -> bool: if account_id in self._balance: return False self._balance[account_id] = 0 self._activity[account_id] = 0 # Insert the 0-activity account immediately so it can appear in get_top_accounts. self._push_ranking(account_id) return True def deposit(self, account_id: str, amount: int) -> bool: # Requiring amount > 0 ensures every update strictly increases activity, # which guarantees older heap entries for the same account become uniquely stale. if amount <= 0 or account_id not in self._balance: return False self._balance[account_id] += amount self._add_activity(account_id, amount) return True def transfer(self, from_id: str, to_id: str, amount: int) -> bool: # Validate every rule up front so failed transfers leave balances and activity untouched. # Rejecting from_id == to_id prevents an account from inflating activity without moving funds. if amount <= 0 or from_id == to_id: return False if from_id not in self._balance or to_id not in self._balance: return False # Strict '<' allows transferring the exact full balance (leaving 0) while blocking overdrafts. if self._balance[from_id] < amount: return False self._balance[from_id] -= amount self._balance[to_id] += amount # Both sender and receiver gain activity on a successful transfer. self._add_activity(from_id, amount) self._add_activity(to_id, amount) return True def get_top_accounts(self, n: int) -> List[str]: # Phase 1: pop up to n live entries, permanently discarding any stale entries we pass. top_entries: List[Tuple[int, str]] = [] while self._heap and len(top_entries) < n: entry = heapq.heappop(self._heap) neg_activity, account_id = entry # An entry is stale if the account's activity has grown since this tuple was pushed. if -neg_activity != self._activity[account_id]: continue top_entries.append(entry) # Phase 2: push the live entries back so reading the leaderboard never mutates it. result: List[str] = [] for entry in top_entries: heapq.heappush(self._heap, entry) result.append(entry[1]) return result def _add_activity(self, account_id: str, amount: int) -> None: self._activity[account_id] += amount self._push_ranking(account_id) def _push_ranking(self, account_id: str) -> None: heapq.heappush(self._heap, (-self._activity[account_id], account_id)) # Once stale entries outnumber live accounts, rebuild in O(N) to bound heap size to <= 2N. if len(self._heap) > 2 * len(self._activity): self._rebuild_ranking() def _rebuild_ranking(self) -> None: self._heap = [] for account_id, activity in self._activity.items(): self._heap.append((-activity, account_id)) heapq.heapify(self._heap) def banking_system(operations: List[str], arguments: List[List]) -> List: bank = BankingSystem() results: List[Any] = [] for operation, args in zip(operations, arguments): if operation == "create_account": results.append(bank.create_account(*args)) elif operation == "deposit": results.append(bank.deposit(*args)) elif operation == "transfer": results.append(bank.transfer(*args)) elif operation == "get_top_accounts": results.append(bank.get_top_accounts(*args)) else: raise ValueError(f"unknown operation: {operation}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of the bank as keeping two records side by side: an official ledger book (_balance and _activity dictionaries) for instant account lookups, and a ranked leaderboard of index cards stored in a min-heap—a priority queue structure that always keeps the smallest tuple at the top and lets you insert or pop the top item in logarithmic time. By writing (-activity, account_id) on each card, the largest activity becomes the most negative number and rises straight to the top, while ties automatically sort by account_id in ascending lexicographical order (character-by-character dictionary order, such as "A" before "B" and "acc10" before "acc2"). Whenever an account's activity grows, instead of searching the whole pile to erase its old card, we use lazy deletion—leaving outdated entries in the heap and skipping them later if their score no longer matches _activity[account_id]—and periodically rebuild the pile once outdated cards outnumber live accounts.
The obvious approach—re-sorting all N accounts on every get_top_accounts(n) call—takes O(N log N) time per query even when n = 3, violating the constraint to beat a full sort across 10^5 accounts. Trying to maintain a sorted Python list with bisect also falls short because inserting or deleting in the middle of an array shifts up to N elements in O(N) time on every deposit or transfer.
Walk through Example 1 step by step:
create_account("vault"),create_account("checking"), andcreate_account("savings")set all three balances and activities to0and push(0, "vault"),(0, "checking"), and(0, "savings")onto_heap.deposit("vault", 300)sets"vault"to balance300and activity300, pushing(-300, "vault")while(0, "vault")stays behind as a stale card.transfer("vault", "checking", 120)moves120from"vault"to"checking"and adds120to both activities (vault: 420, checking: 120, savings: 0), pushing(-420, "vault")and(-120, "checking").get_top_accounts(3)pops(-420, "vault")(live), skips(-300, "vault")(stale), pops(-120, "checking")(live), skips(0, "checking")(stale), pops(0, "savings")(live), pushes those three live cards back onto_heap, and returns["vault", "checking", "savings"].
Complexity
Let N be the number of created accounts and k = min(max(n, 0), N) be the number of accounts returned by get_top_accounts(n). Bounds are stated in amortized time, meaning the average cost per operation over any worst-case sequence of calls.
create_account,deposit, andtransfer: O(log N) amortized time. Dictionary checks and updates take O(1) average time, and each operation performs one or two heap pushes of cost O(log N) because periodic compaction keeps the heap size at most 2N + 1. Rebuilding the heap withheapifytakes O(N) time, but it triggers only after at least N + 1 new pushes since the previous rebuild, spreading out to O(1) extra work per push.get_top_accounts(n): O(k log N) amortized time. Popping k live entries and pushing them back takes 2k heap operations of O(log N) each; any stale entries popped along the way are discarded permanently, so each stale entry is paid for at most once by the update that created it.- Space: O(N), because
_balanceand_activitystore N entries each and_rebuild_rankingprevents_heapfrom ever exceeding 2N entries between calls.
Edge cases
nlarger than the number of accounts,n <= 0, or an empty bank:while self._heap and len(top_entries) < nnaturally stops when the heap runs out (returning all accounts) and never executes whenn <= 0or the bank is empty (returning[]).- Accounts with
0activity: pushing(0, account_id)insidecreate_accountensures newly created accounts still appear inget_top_accounts, sorted by ascending ID. - Lexicographical tie-breaking: strings compare character by character (
"acc10"comes before"acc2"because'1' < '2'). - Exact full-balance transfer (
balance == amount): checkingself._balance[from_id] < amountallows draining an account down to0while rejectingamount = balance + 1. - Duplicate
create_accountor failed deposits/transfers: returningFalsebefore mutating state preserves existing balances, activities, and rankings. - Self-transfers (
from_id == to_id) and non-positive amounts (amount <= 0): both returnFalse; requiringamount > 0also preserves the invariant that every update strictly increases activity so an account never has two identical live tuples in_heap.
Common mistakes
- Forgetting to push valid entries back in
get_top_accounts:heappopremoves items fromself._heap, so failing to pushtop_entriesback erases the topnaccounts from future queries! - Crediting activity only to the sender on
transfer: the specification defines activity as deposits plus transfers both sent and received, so bothfrom_idandto_idgainamount. - Reversing tie-breaker order with a simulated max-heap: if you negate or invert comparison on the entire tuple instead of negating only
activityin(-activity, account_id), tied IDs come out in descending ("Z"before"A") order. - Mutating the sender's balance before checking whether
to_idexists: leaves money missing ifto_idis invalid. - Claiming
bisect.insort+list.removeis O(log N): binary search finds the index in O(log N), but shifting elements in a contiguous Pythonliststill takes O(N) time per update. - Using slice
ranking[:n]without guarding negativen: in Pythonitems[:-1]returns everything except the last item instead of[].
Alternative approaches
- Balanced binary search tree / sorted set (
sortedcontainers.SortedListin Python,TreeSetin Java,std::setin C++): a sorted set—an ordered collection that keeps unique elements sorted while supporting insert and delete in O(log N) time—lets each update remove(-old_activity, id)and insert(-new_activity, id)directly, keeping memory at exactly N entries and answeringget_top_accounts(n)in O(k + log N) time without lazy deletion. heapq.nsmallest(n, ((-act, acc_id) for acc_id, act in self._activity.items()))on demand: requires zero heap maintenance on updates (O(1) updates) and beats a full sort whennis small (O(N log k)per query), though it still scans all N accounts on every query and becomes slow under heavy query traffic.
Follow-up questions
- What synchronization strategy prevents race conditions and deadlocks when many worker threads execute transfers concurrently? Without synchronization, two threads transferring out of
"A"at once can both pass the balance check and overdraw the account, while acquiring per-account locks in arbitrary order (transfer("A", "B")locking A then B whiletransfer("B", "A")locks B then A) causes a deadlock—a freeze where two threads wait forever for each other's lock. Prevent deadlocks by always locking the two accounts in sorted ID order (min(from_id, to_id)first, thenmax(from_id, to_id)), and send activity deltas onto an asynchronous queue consumed by a single leaderboard worker (or use sharded single-threaded account partitions) so transfers do not contend on a single global heap lock. - How would you store balances durably and keep rankings fast once the platform scales to tens of millions of accounts? Store authoritative balances and an append-only transaction ledger in an ACID relational database (such as PostgreSQL) so every transfer debits and credits atomically inside one database transaction. Maintain the live leaderboard in a distributed in-memory sorted set like Redis (
ZINCRBY leaderboard -amount account_idso negated scores keep highest activity first while ties sort by ascending ID viaZRANGE leaderboard 0 n-1), streaming committed database events via a transactional outbox so the Redis leaderboard can always be replayed or rebuilt from the database after a crash. - What needs to change if rankings are computed over a rolling 30-day window rather than lifetime volume? Append each successful transaction to a chronological queue of
(timestamp, account_id, amount)events (or aggregate into 30 daily buckets per account if day-level granularity suffices) and subtract expired events from_activityas the 30-day window slides forward. Because an account's 30-day activity can now decrease back to an earlier value, an old heap tuple could accidentally match the current_activityagain; fix this either by adding a monotonically increasing per-account version number(-activity, account_id, version)to heap tuples or by maintaining a true sorted set that removes old entries on every change.
Follow-up questions
- What synchronization strategy prevents race conditions and deadlocks when many worker threads execute transfers concurrently?
- How would you store balances durably and keep rankings fast once the platform scales to tens of millions of accounts?
- What needs to change if rankings are computed over a rolling 30-day window rather than lifetime volume?
Similar questions
- Matrix Row and Rotation Commands
- Bash Script for Reproducible Python Virtual Environments
- Point Obstacles and Clear Span Queries
- Circular Peak-and-Valley Array Check
- Elapsed Minutes Since Previous Departure
- Odd Zero-Digit Frequency Count
More Capital One interview questions
- Distinct Border Value Sum Across Maximum-Sum Square Frames Hard
- Virtual Payment Cards: Trade-Offs, Validation Rules, and Filter Debugging Medium
- Virtual Payment Cards: Rule Validation, State Tracking, and Edge Cases Medium Pro
- Count Fixed-Length Subarrays Matching Neighbor Comparison Signs Medium Pro
- Ad Engagement and ISO-Week PivotTable Analysis Medium Pro
- Point Obstacles and Clear Span Queries Medium Pro
- Leading a Technical Product from Concept to Launch Medium Pro
- High-Impact Win, Production Failure, and Enabling Others Medium Pro
- TV Series Contract Renewal and Divestiture Economics Medium Pro
- Forward-Fill Log Dates for Peak Viewing Slot Medium Pro