KatInterview

Design a Time-Series Cloud Credit Ledger

Data Structure DesignModel answer
HardModel answerData Structure DesignData Structure DesignHeapUnion Find

Last updated

Design an in-memory cloud billing system supporting delayed cashback rebates, account consolidation, point-in-time historical balance queries, and spend leaderboards.

You are tasked with building an in-memory credit ledger system, CloudCreditLedger, that manages balances for cloud services across discrete non-decreasing timestamps.

The ledger must process top-ups, charges with delayed percentage-based rebates, account merges, historical point-in-time balance queries, and a spending leaderboard.

System Requirements

  1. Rebate Logic:

    • Charges may trigger a delayed rebate calculated as: rebate_amount = floor(amount * rebate_pct / 100).
    • The rebate must be credited back at timestamp + rebate_delay.
    • Before any operation at timestamp $T$ is processed, all pending rebates scheduled for time $t \le T$ must be fully applied.
    • If multiple rebates mature at the exact same timestamp, process them in the order their originating charges occurred.
    • Rebates must be credited to the current canonical account (taking merges into account) and do not reduce an account's gross spend record.
  2. Account Consolidation (Merges):

    • Merging source_id into target_id at timestamp $T$ transfers source_id's remaining balance at $T$ into target_id.
    • Any future operation referencing source_id is automatically redirected to target_id.
    • Merges are transitive (if A merges into B, and B merges into C, operations on A resolve to C).
    • Merging two accounts combines their historical gross spending totals into target_id.
    • Historical queries for source_id at query_time < T must reflect the exact balance source_id possessed at query_time prior to the merge.
  3. Leaderboard & Historical Queries:

    • The spending leaderboard ranks active canonical accounts by total gross credits spent through successful charges. Ties are broken lexicographically by the canonical account ID.
    • Historical balance queries return the balance an account held at a specified query_time. If the account was merged at time $M$, historical queries for query_time < M evaluate the unmerged account; queries for query_time >= M resolve to the merged canonical target at query_time.

Class Interface

class CloudCreditLedger:
    def __init__(self):
        pass

    def top_up(self, timestamp: int, account_id: str, amount: int) -> bool:
        """Credits amount to account_id's balance. Returns True if amount > 0, else False."""
        pass

    def charge(self, timestamp: int, account_id: str, amount: int, rebate_delay: int, rebate_pct: int) -> bool:
        """Attempts to charge amount to account_id. 
        If canonical balance >= amount, deducts amount, records spending,
        and schedules a rebate of floor(amount * rebate_pct / 100) at timestamp + rebate_delay.
        Returns True on success, False if account does not exist or insufficient balance."""
        pass

    def merge_accounts(self, timestamp: int, source_id: str, target_id: str) -> bool:
        """Merges source_id into target_id. Returns False if source_id == target_id,
        if either account does not exist, or if both resolve to the same root.
        Transfers remaining balance and accumulated spend to target_id."""
        pass

    def get_balance(self, timestamp: int, account_id: str) -> int:
        """Returns the balance of account_id's current canonical account at timestamp.
        Returns -1 if the account does not exist."""
        pass

    def get_historical_balance(self, timestamp: int, account_id: str, query_time: int) -> int:
        """Returns the balance account_id held at query_time (query_time <= timestamp).
        Only resolves to merge target if merge occurred at or before query_time.
        Returns -1 if account did not exist at query_time."""
        pass

    def get_top_spenders(self, timestamp: int, k: int) -> list[str]:
        """Returns up to k canonical account IDs with highest total gross spend.
        Ties are resolved alphabetically by account ID."""
        pass

Constraints

  • Timestamps across incoming method calls are strictly non-decreasing: $T_{prev} \le T_{curr}$.
  • $0 \le \text{query_time} \le \text{timestamp} \le 10^9$
  • $1 \le \text{amount} \le 10^6$
  • $0 \le \text{rebate_delay} \le 10^6$, $0 \le \text{rebate_pct} \le 100$
  • At most $100,000$ total API operations.

Hints

Hint 1

Use a min-heap to queue future rebates ordered by (scheduled_time, sequence_id). Flush all rebates with scheduled_time <= current_timestamp at the start of every public operation.

Hint 2

Maintain two separate representations for account links: a Disjoint Set Union (Union-Find) structure for O(1) current canonical account resolution, and an uncompressed directed graph with edge timestamps for temporal traversal during historical lookups.

Hint 3

Store balance history per account as a pair of parallel arrays (timestamps and balances). Since operation timestamps are non-decreasing, these lists remain naturally sorted, allowing O(log N) point-in-time queries via binary search (bisect_right).