Katkat

Build a Banking System with Activity Rankings

Capital OneSoftware Engineer · Onsite

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

  1. create_account(account_id: str): Initializes a new account with a balance of 0 and activity of 0. Returns True if successful, False if the ID already exists.
  2. deposit(account_id: str, amount: int): Adds amount to the account balance and updates the account's activity by amount. Returns True if successful, False if the account does not exist.
  3. transfer(from_id: str, to_id: str, amount: int): If both accounts exist and the source account has sufficient funds, subtracts amount from the source, adds amount to the destination, and adds amount to the activity of both accounts. Returns True if successful, False otherwise.
  4. get_top_accounts(n: int): Returns a list of the n account 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_id is a unique string.
  • amount is a positive integer.
  • Total number of accounts N <= 10^5.
  • get_top_accounts should 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?