Katkat

Implement a Timestamped Banking System

MetaSoftware Engineer · Online Assessment

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

  1. deposit(account_id, amount, timestamp): Adds amount to the account at the given timestamp. If a transaction already exists for this exact timestamp, update it.
  2. get_balance(account_id, timestamp): Returns the balance of the account at the exact moment of the provided timestamp. If no transaction exists exactly at this timestamp, return the balance as it was after the most recent transaction prior to this timestamp (or 0 if none exist).
  3. get_top_accounts(timestamp, k): Returns a list of the top k account_ids based on their balance at the given timestamp. If two accounts have the same balance, order by account_id ascending.

Constraints

  • account_id: String (alphanumeric).
  • amount: Integer.
  • timestamp: Integer (non-negative).
  • Total operations up to 10^5.
  • k will 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?