Time-Ordered Credit Bucket Manager
Data Structure DesignModel answerLast updated
Build a ledger tracking credit buckets with expiration windows, supporting out-of-order events, priority-based consumption, and point-in-time balance queries.
You are building a credit management system where users accumulate credit buckets that become valid at specific times and expire after a fixed duration. The system must handle events arriving in any order.
Implement a ledger with three operations:
add_credit(id, amount, time_stamp, expiration)
Register a new credit bucket with a unique string identifier id containing amount units. The credit is valid starting at time_stamp and expires at time_stamp + expiration (half-open interval: valid at the start time, invalid at the expiration time).
charge(amount, time_stamp)
Deduct up to amount units from credits valid at time_stamp. Always consume from the bucket expiring soonest. When multiple buckets share the same expiration time, prefer the one that became valid earliest. If there is still a tie, pick the lexicographically smallest id. Return the total amount successfully deducted (may be less than requested if insufficient valid credits exist).
get_balance(time_stamp)
Return the sum of all remaining credit across buckets that are valid at time_stamp.
Events may arrive in arbitrary chronological order. A charge or add_credit with an earlier timestamp than previous operations must still produce correct results for all subsequent queries.
Example:
ledger.add_credit("A", 100, 50, 40) # valid [50, 90)
ledger.add_credit("B", 100, 60, 40) # valid [60, 100)
ledger.add_credit("C", 100, 55, 40) # valid [55, 95)
ledger.add_credit("D", 100, 65, 40) # valid [65, 105)
ledger.charge(250, 65)
# At time 65, valid buckets sorted by priority:
# A (expires 90), C (expires 95), B (expires 100), D (expires 105)
# Consumes: A→100, C→100, B→50
# Returns: 250
ledger.get_balance(50) # => 100 (only A)
ledger.get_balance(65) # => 150 (B has 50 left, D has 100)
ledger.get_balance(100) # => 100 (only D remains valid)
Specify the time and space complexity of your solution. Discuss how you handle out-of-order arrivals efficiently.
Hints
Hint 1
Think of the problem as replaying a timeline in chronological order regardless of arrival sequence
Hint 2
Use a priority queue to manage which credit bucket to consume from next during a charge operation
Hint 3
Consider materializing balance changes at specific time boundaries to answer queries without re-simulating the entire history
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to separate arrival order from logical order. The correct behavior is determined entirely by timestamps, so we maintain all events in a sorted timeline and replay them in chronological sequence whenever state needs updating.
High-Level Strategy
-
Maintain a sorted event log: Store every
add_creditandchargeevent in a list sorted by(timestamp, event_type, sequence_id). Theevent_typedistinguishes adds (0) from charges (1) so that credits starting at timetare registered before any charge at timet. Thesequence_idbreaks ties between multiple charges at the same instant. -
Replay the timeline: Walk through events in sorted order, maintaining a min-heap of active credits keyed by
(expiration_time, activation_time, id). This heap ordering ensures we always consume the highest-priority bucket first. For each charge, remove expired credits from the heap, then drain from the top until the charge is satisfied or no credits remain. -
Precompute balance intervals: Convert the replay into a set of balance changes at specific time boundaries. A credit contributes
+amountstarting at its activation time and-amountstarting at its expiration time. Each consumption contributes-consumed_amountstarting at the charge time. Build a sorted list of time boundaries with prefix sums so thatget_balance(t)becomes a binary search. -
Lazy rebuild: Mark the state dirty on any insert. The next
chargeorget_balancetriggers a full replay and recomputes the interval structure. This trades off per-operation latency for correctness under retroactive edits.
Why This Works
- Chronological replay produces the true outcome: Sorting by
(time, type, seq)establishes a total order consistent with the problem semantics. Credits are inserted before same-time charges due to the type field. - Priority queue enforces consumption rules: The heap key
(expiration, activation, id)exactly matches the tie-breaking specification. Only credits withexpiration > charge_timeremain in the heap during consumption. - Interval decomposition is exact: At any moment
t, a credit contributes its remaining balance if and only ifactivation ≤ t < expiration. Summing interval contributions across all credits and subtracting all consumptions up totyields the correct balance.
Complexity
Let n be the total number of events.
add_credit: O(n) per call. Insert into sorted list and mark dirty.charge: O(n log n) per call. Insert into sorted list, then replay the entire timeline with heap operations.get_balance: O(log n) when state is clean (binary search). O(n log n) on first query after modifications (triggers rebuild).- Space: O(n) for events, heap, and interval boundaries.
Handling Out-of-Order Events
When a new event arrives with a timestamp earlier than previously processed events, the entire history may change because a retroactive credit could shift which buckets were consumed by later charges. The solution handles this by invalidating cached state and replaying from scratch. This is simple and correct.
Optimization ideas (beyond interview scope, but worth mentioning):
- Monotonic fast path: If new events always have timestamps ≥ the last processed time, apply them incrementally without full replay.
- Checkpointing: Snapshot heap state every √n events and replay only from the nearest checkpoint before the insertion point.
Edge Cases and Clarifications
- Credits with
expiration ≤ 0oramount ≤ 0contribute nothing. - A charge larger than available balance returns the partial amount actually deducted.
- A credit expiring exactly at charge time (
expiration == charge_time) is not consumed because the interval is half-open. - A credit starting exactly at charge time is consumed.
- Multiple charges at the same timestamp are processed in arrival order.
- Duplicate credit IDs should be rejected (or handled by your choice of collision strategy).
- Queries at times with no events return 0 or the most recent balance.
Code
import bisect
import heapq
from collections import defaultdict
class CreditLedger:
ADD, CHARGE = 0, 1
def __init__(self):
self.events = [] # sorted: (time, kind, seq, data)
self.seq_counter = 0
self.seen_ids = set()
self.needs_rebuild = False
self.breakpoints = [] # sorted times
self.balances = [] # balance at each breakpoint
self.charge_results = {} # seq -> amount charged
def add_credit(self, id, amount, time_stamp, expiration):
if id in self.seen_ids:
raise ValueError(f"Duplicate credit ID: {id}")
self.seen_ids.add(id)
self.seq_counter += 1
end_time = time_stamp + expiration
bisect.insort(self.events,
(time_stamp, self.ADD, self.seq_counter,
(id, amount, end_time)))
self.needs_rebuild = True
def charge(self, amount, time_stamp):
self.seq_counter += 1
seq = self.seq_counter
bisect.insort(self.events,
(time_stamp, self.CHARGE, seq, amount))
self.needs_rebuild = True
self._rebuild()
return self.charge_results[seq]
def get_balance(self, time_stamp):
if self.needs_rebuild:
self._rebuild()
idx = bisect.bisect_right(self.breakpoints, time_stamp) - 1
return self.balances[idx] if idx >= 0 else 0
def _rebuild(self):
heap = []
deltas = defaultdict(int)
charged = {}
for t, kind, seq, data in self.events:
if kind == self.ADD:
cid, amt, end = data
if amt > 0 and end > t:
deltas[t] += amt
deltas[end] -= amt
heapq.heappush(heap, [end, t, cid, amt])
else:
requested = data
# Remove expired credits
while heap and heap[0][0] <= t:
heapq.heappop(heap)
# Consume from active credits
remaining = requested
while remaining > 0 and heap:
entry = heapq.heappop(heap)
expire, start, cid, available = entry
take = min(remaining, available)
deltas[t] -= take
deltas[expire] += take
remaining -= take
if available > take:
entry[3] = available - take
heapq.heappush(heap, entry)
charged[seq] = requested - remaining
# Build prefix sums
times = sorted(deltas.keys())
self.breakpoints = times
self.balances = []
total = 0
for time in times:
total += deltas[time]
self.balances.append(total)
self.charge_results = charged
self.needs_rebuild = False
Time complexity: O(n log n) per rebuild (sorting events, heap operations). Each operation that modifies state triggers a rebuild on the next query or charge.
Space complexity: O(n) for events and interval data.
This solution is clear, correct, and appropriate for a technical screen. In a real production system with high write rates, you would layer on incremental updates or segment the timeline into immutable chunks.