Build a Banking System with Activity Rankings
Capital OneSoftware Engineer · OnsiteLast updated
This problem tests your ability to design a system that maintains account state and dynamically updates an ordered leaderboard of account activity using efficient data structures.
Problem Statement
Design an in-memory banking system that tracks account balances and total transaction volumes. An account's "activity" is defined as the sum of all successful deposit and transfer amounts (both sent and received) involving that account.
Implement the following methods in a class BankingSystem:
create_account(account_id: str): Initializes a new account with a balance of 0 and activity of 0. ReturnsTrueif successful,Falseif the ID already exists.deposit(account_id: str, amount: int): Addsamountto the account balance and updates the account's activity byamount. ReturnsTrueif successful,Falseif the account does not exist.transfer(from_id: str, to_id: str, amount: int): If both accounts exist and the source account has sufficient funds, subtractsamountfrom the source, addsamountto the destination, and addsamountto the activity of both accounts. ReturnsTrueif successful,Falseotherwise.get_top_accounts(n: int): Returns a list of thenaccount IDs with the highest activity. If two accounts have the same activity, break ties by sorting IDs lexicographically in ascending order.
Example
bank = BankingSystem()
bank.create_account("A")
bank.create_account("B")
bank.deposit("A", 100) # A: balance 100, activity 100
bank.transfer("A", "B", 50) # A: bal 50, act 150; B: bal 50, act 50
bank.get_top_accounts(2) # Returns ["A", "B"]
Constraints
account_idis a unique string.amountis a positive integer.- Total number of accounts
N <= 10^5. get_top_accountsshould perform better than a full sort of all accounts on every call.
Hints
Hint 1
Use a hash map to store account balances and activity scores for O(1) lookups.
Hint 2
To handle activity rankings, consider maintaining a sorted set (or equivalent balanced BST) that stores pairs of `(-activity, account_id)`.
Hint 3
Updating an activity score in a sorted set requires removing the old entry and inserting the updated one to keep the structure balanced.
Follow-up questions
- How would you handle high concurrency if multiple threads perform transfers simultaneously?
- If the number of accounts grows to millions, how would you persist this data while maintaining the leaderboard?
- How would you modify the system to track the 'last 30 days' of activity instead of 'all-time' activity?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.