Implement a Timestamped Banking System
MetaSoftware Engineer · Online AssessmentLast updated
This problem tests the ability to manage time-series data using efficient lookups and range queries, specifically requiring a balance between transactional updates and historical state retrieval.
Problem Statement
Design a system that tracks bank account balances over time. You need to support the following operations:
deposit(account_id, amount, timestamp): Addsamountto the account at the giventimestamp. If a transaction already exists for this exact timestamp, update it.get_balance(account_id, timestamp): Returns the balance of the account at the exact moment of the providedtimestamp. If no transaction exists exactly at thistimestamp, return the balance as it was after the most recent transaction prior to thistimestamp(or 0 if none exist).get_top_accounts(timestamp, k): Returns a list of the topkaccount_idsbased on their balance at the giventimestamp. If two accounts have the same balance, order byaccount_idascending.
Constraints
account_id: String (alphanumeric).amount: Integer.timestamp: Integer (non-negative).- Total operations up to 10^5.
kwill be reasonable for output.
Examples
Example 1:
deposit("A", 100, 1)
deposit("B", 200, 2)
get_balance("A", 5) -> returns 100
get_balance("A", 0) -> returns 0
get_top_accounts(3, 1) -> returns ["B"] (B has 200, A has 100)
Implementation
class BankSystem:
def __init__(self):
pass
def deposit(self, account_id, amount, timestamp):
pass
def get_balance(self, account_id, timestamp):
pass
def get_top_accounts(self, timestamp, k):
pass
Hints
Hint 1
Use a dictionary of sorted lists (or a balanced BST) to store transactions for each account to allow for efficient binary search of historical balances.
Hint 2
For the top-K query, note that balances change at discrete timestamps; you may need a way to track the state of all accounts at any given time.
Hint 3
Since calculating top-K across all accounts at every timestamp is expensive, consider using a data structure like a Fenwick tree or a Segment Tree if the total number of accounts is small, or a time-indexed snapshot approach.
Follow-up questions
- How would you optimize `get_top_accounts` if the number of accounts is significantly larger than the number of transactions?
- What changes are needed to support `withdraw` operations that must ensure the balance never drops below zero?
- How would you handle the system if timestamps were not strictly increasing?
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.