KatInterview

Time-Ordered Credit Bucket Manager

Data Structure DesignModel answer
MediumModel answerData Structure Designheapsevent-orderingtime-series

Last 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