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:
  1. create_account(account_id: str) -> bool — Registers account_id starting at 0 balance and 0 activity and returns True. If account_id is already registered, leaves the existing account unchanged and returns False.
  2. deposit(account_id: str, amount: int) -> bool — Credits amount to account_id's balance and increases its activity by amount, returning True. Returns False without modifying state if account_id does not exist (or amount <= 0).
  3. transfer(from_id: str, to_id: str, amount: int) -> bool — Moves amount from from_id to to_id only when both accounts exist, from_id != to_id, amount > 0, and from_id's current balance is at least amount. On success, from_id's balance decreases by amount, to_id's balance increases by amount, both accounts' activity totals increase by amount, and the call returns True. Otherwise no balances or activity totals change and the call returns False.
  4. get_top_accounts(n: int) -> List[str] — Returns up to n account IDs ordered from highest activity to lowest. Break ties between equal activity totals by account_id in ascending lexicographical (ASCII string) order. Return all existing accounts when fewer than n exist, and [] when n <= 0 or 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_id is a non-empty string.
  • amount >= 1 for valid deposits and transfers.
  • At most 10^5 accounts are created (N <= 10^5), and total operations are at most 10^5.
  • get_top_accounts(n) must run asymptotically faster than sorting all N accounts from scratch on each query.

Step-by-step walkthrough

  1. Understand the account rules and leaderboard order

    We need to build an in-memory BankingSystem that tracks two numbers for each account:

    • balance: how much money the account currently holds (starts at 0).
    • activity: the cumulative sum of all successful deposits into the account plus all successful transfers either sent from or received by the account (starts at 0).

    Four methods operate on the bank, and the automated judge calls them through banking_system(operations, arguments):

    1. create_account(account_id) — creates the account at 0 balance and 0 activity, or returns False if account_id already exists (leaving the existing account untouched).
    2. deposit(account_id, amount) — adds amount to both balance and activity, or returns False if the account is missing.
    3. transfer(from_id, to_id, amount) — checks that both accounts exist and balance[from_id] >= amount; if so, moves amount from from_id to to_id and adds amount to both accounts' activity.
    4. get_top_accounts(n) — returns up to n account IDs ordered by highest activity first, breaking ties by account_id in 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 transfer rejects self-transfers (from_id == to_id) and non-positive amounts (amount <= 0) so no account can inflate its activity without moving real funds.

  2. Why sorting on every query is too slow

    With two dictionaries (_balance and _activity), create_account, deposit, and transfer each take O(1) time. The naive way to answer get_top_accounts(n) is to build [(-activity, account_id) ...] across all N accounts and call .sort() on every query.

    With up to N = 10^5 accounts, sorting every account on each query costs O(N log N) time even when n = 3—and the problem explicitly requires get_top_accounts to beat a full sort on every call. Keeping a Python list sorted with bisect does not fix the bottleneck either, because list.insert and del still shift up to N elements in O(N) time per update.

  3. Key idea: a min-heap of (-activity, id) with lazy deletion

    Python's heapq module provides a min-heap—a binary tree stored in a list that always keeps the smallest item at index 0 and 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 activity produces a more negative -activity, so the most active account pops first.
    • Equal activity ties on -activity and falls back to comparing account_id in 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 onto self._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 matching self._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 from self._activity in O(N) time using heapq.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.
  4. Implement account creation, deposits, and transfers

    Let's write BankingSystem.__init__ and the three state-changing methods first. Notice how create_account pushes (0, account_id) right away so brand-new accounts with 0 activity still appear in get_top_accounts, and transfer validates 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 True
    
  5. Implement lazy-heap updates and top-n queries

    In get_top_accounts(n), we pop tuples from self._heap until we have collected n live entries (or the heap runs out). Any stale entry we pop is discarded permanently; the live entries we keep must be pushed back into self._heap before 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 one BankingSystem and dispatches each operation name to its method.

  6. 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.

  7. 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:

  1. create_account("vault"), create_account("checking"), and create_account("savings") set all three balances and activities to 0 and push (0, "vault"), (0, "checking"), and (0, "savings") onto _heap.
  2. deposit("vault", 300) sets "vault" to balance 300 and activity 300, pushing (-300, "vault") while (0, "vault") stays behind as a stale card.
  3. transfer("vault", "checking", 120) moves 120 from "vault" to "checking" and adds 120 to both activities (vault: 420, checking: 120, savings: 0), pushing (-420, "vault") and (-120, "checking").
  4. 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, and transfer: 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 with heapify takes 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 _balance and _activity store N entries each and _rebuild_ranking prevents _heap from ever exceeding 2N entries between calls.

Edge cases

  • n larger than the number of accounts, n <= 0, or an empty bank: while self._heap and len(top_entries) < n naturally stops when the heap runs out (returning all accounts) and never executes when n <= 0 or the bank is empty (returning []).
  • Accounts with 0 activity: pushing (0, account_id) inside create_account ensures newly created accounts still appear in get_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): checking self._balance[from_id] < amount allows draining an account down to 0 while rejecting amount = balance + 1.
  • Duplicate create_account or failed deposits/transfers: returning False before mutating state preserves existing balances, activities, and rankings.
  • Self-transfers (from_id == to_id) and non-positive amounts (amount <= 0): both return False; requiring amount > 0 also 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: heappop removes items from self._heap, so failing to push top_entries back erases the top n accounts from future queries!
  • Crediting activity only to the sender on transfer: the specification defines activity as deposits plus transfers both sent and received, so both from_id and to_id gain amount.
  • Reversing tie-breaker order with a simulated max-heap: if you negate or invert comparison on the entire tuple instead of negating only activity in (-activity, account_id), tied IDs come out in descending ("Z" before "A") order.
  • Mutating the sender's balance before checking whether to_id exists: leaves money missing if to_id is invalid.
  • Claiming bisect.insort + list.remove is O(log N): binary search finds the index in O(log N), but shifting elements in a contiguous Python list still takes O(N) time per update.
  • Using slice ranking[:n] without guarding negative n: in Python items[:-1] returns everything except the last item instead of [].

Alternative approaches

  • Balanced binary search tree / sorted set (sortedcontainers.SortedList in Python, TreeSet in Java, std::set in 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 answering get_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 when n is 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 while transfer("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, then max(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_id so negated scores keep highest activity first while ties sort by ascending ID via ZRANGE 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 _activity as 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 _activity again; 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

Similar questions

More Capital One interview questions

All 268 Capital One questions →