Design a Time-Series Cloud Credit Ledger
Data Structure DesignModel answerLast 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
-
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.
- Charges may trigger a delayed rebate calculated as:
-
Account Consolidation (Merges):
- Merging
source_idintotarget_idat timestamp $T$ transferssource_id's remaining balance at $T$ intotarget_id. - Any future operation referencing
source_idis automatically redirected totarget_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_idatquery_time < Tmust reflect the exact balancesource_idpossessed atquery_timeprior to the merge.
- Merging
-
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 forquery_time < Mevaluate the unmerged account; queries forquery_time >= Mresolve to the merged canonical target atquery_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).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The design requires combining four distinct techniques to handle asynchronous events, dynamic aliases, point-in-time history, and aggregated metrics:
-
Lazy Event Processing (Min-Heap for Rebates): Future rebates are stored in a min-heap ordered by
(scheduled_time, sequence_id). Before handling any API call at time $T$, a internal helper_flush(T)pops and applies all rebates scheduled at or before $T$. Using a monotonic global sequence counter breaks ties deterministically in order of charge creation. Applying rebates lazily is correct because method invocation timestamps are non-decreasing. -
Canonical Alias Resolution (Union-Find): Current account mappings use standard Disjoint Set Union (DSU) with path compression. This enables near $O(1)$ lookup for the current canonical parent of any account.
-
Time-Aware Merge History: Path compression in standard DSU destroys historical edge creation times. To support
get_historical_balance, we maintain a separate merge log (merged_into[node],merged_at[node]) keeping the uncompressed merge graph. When evaluatingget_historical_balanceatquery_time, we traverse merge edges if and only ifmerged_at[node] <= query_time. -
Point-in-Time Historical Snapshots (Binary Search): Each account stores snapshot timelines of balance mutations:
times[acc]andbals[acc]. Because timestamps enter non-decreasingly, these lists stay sorted. Evaluating historical balance atquery_timerequires performingbisect_rightto find the latest recorded state at or beforequery_time.
Python 3 Implementation
import heapq
from bisect import bisect_right
class CloudCreditLedger:
def __init__(self):
# Union-Find for current canonical resolution
self.parent = {}
# Merge graph preserved without path compression for historical lookups
self.merged_into = {}
self.merged_at = {}
# Account state metadata
self.created_at = {}
self.balance = {} # Keyed by canonical root
self.spent = {} # Gross expenditure, keyed by canonical root
# Historical snapshot timelines per account ID
self.times = {} # acc_id -> list of timestamps
self.bals = {} # acc_id -> list of balance states
self.active_roots = set()
self.rebate_heap = [] # Elements: (scheduled_time, sequence_id, source_acc, rebate_amount)
self.seq_counter = 0
def _find(self, acc: str) -> str:
"""Find canonical root with path compression."""
root = acc
while self.parent[root] != root:
root = self.parent[root]
curr = acc
while self.parent[curr] != root:
nxt = self.parent[curr]
self.parent[curr] = root
curr = nxt
return root
def _record_snapshot(self, acc: str, t: int):
"""Append or overwrite balance snapshot for acc at timestamp t."""
ts, bs = self.times[acc], self.bals[acc]
if ts and ts[-1] == t:
bs[-1] = self.balance[acc]
else:
ts.append(t)
bs.append(self.balance[acc])
def _flush(self, current_time: int):
"""Process all rebates due on or before current_time."""
while self.rebate_heap and self.rebate_heap[0][0] <= current_time:
sched_time, _, orig_acc, amt = heapq.heappop(self.rebate_heap)
target = self._find(orig_acc)
self.balance[target] += amt
self._record_snapshot(target, sched_time)
def top_up(self, timestamp: int, account_id: str, amount: int) -> bool:
self._flush(timestamp)
if amount <= 0:
return False
if account_id not in self.parent:
self.parent[account_id] = account_id
self.created_at[account_id] = timestamp
self.balance[account_id] = 0
self.spent[account_id] = 0
self.times[account_id] = []
self.bals[account_id] = []
self.active_roots.add(account_id)
canonical = self._find(account_id)
self.balance[canonical] += amount
self._record_snapshot(canonical, timestamp)
return True
def charge(self, timestamp: int, account_id: str, amount: int, rebate_delay: int, rebate_pct: int) -> bool:
self._flush(timestamp)
if amount <= 0 or account_id not in self.parent:
return False
canonical = self._find(account_id)
if self.balance[canonical] < amount:
return False
self.balance[canonical] -= amount
self.spent[canonical] += amount
self._record_snapshot(canonical, timestamp)
rebate_val = (amount * rebate_pct) // 100
if rebate_val > 0:
due_time = timestamp + rebate_delay
heapq.heappush(self.rebate_heap, (due_time, self.seq_counter, canonical, rebate_val))
self.seq_counter += 1
return True
def merge_accounts(self, timestamp: int, source_id: str, target_id: str) -> bool:
self._flush(timestamp)
if source_id not in self.parent or target_id not in self.parent:
return False
root_src = self._find(source_id)
root_tgt = self._find(target_id)
if root_src == root_tgt:
return False
# Record uncompressed merge history for root_src
self.merged_into[root_src] = root_tgt
self.merged_at[root_src] = timestamp
# Update current DSU mapping
self.parent[root_src] = root_tgt
self.active_roots.remove(root_src)
# Transfer balance and spend to target
self.balance[root_tgt] += self.balance[root_src]
self.spent[root_tgt] += self.spent[root_src]
# Zero out source and snapshot both accounts
self.balance[root_src] = 0
self._record_snapshot(root_src, timestamp)
self._record_snapshot(root_tgt, timestamp)
return True
def get_balance(self, timestamp: int, account_id: str) -> int:
self._flush(timestamp)
if account_id not in self.parent:
return -1
canonical = self._find(account_id)
return self.balance[canonical]
def get_historical_balance(self, timestamp: int, account_id: str, query_time: int) -> int:
self._flush(timestamp)
if account_id not in self.parent or query_time < self.created_at[account_id]:
return -1
# Walk merge history up to query_time
curr = account_id
while curr in self.merged_into and self.merged_at[curr] <= query_time:
curr = self.merged_into[curr]
# Binary search for balance at query_time
ts = self.times[curr]
bs = self.bals[curr]
idx = bisect_right(ts, query_time) - 1
if idx < 0:
return 0
return bs[idx]
def get_top_spenders(self, timestamp: int, k: int) -> list[str]:
self._flush(timestamp)
# Rank roots primarily by spent DESC, secondarily by acc_id ASC
sorted_roots = sorted(self.active_roots, key=lambda acc: (-self.spent[acc], acc))
return sorted_roots[:k]
Complexity Analysis
-
Time Complexity:
top_up,charge,get_balance: $O(\log R + \alpha(N))$ per operation, where $R$ is the number of pending rebates (heap operations) and $\alpha$ is the Inverse Ackermann function for Union-Find lookups.merge_accounts: $O(\log R + \alpha(N))$.get_historical_balance: $O(\log R + D + \log S)$, where $D$ is the merge-chain depth and $S$ is the number of historical snapshots for that account. Binary search takes $O(\log S)$.get_top_spenders: $O(A \log A)$ where $A$ is the count of active canonical roots (or $O(A \log k)$ using a min-heap).
-
Space Complexity:
- $O(N + R)$ overall, storing $O(1)$ space per account node, snapshot history proportional to the number of successful operations $N$, and $O(R)$ for queued rebates.