Billing Ledger with Credit Prioritization and Backdating
Data Structure DesignAuto-graded · 23 test casesLast updated
Process billing events where credits pay usage before subscription fees, supporting out-of-order event insertion with selective recomputation.
You're building a billing ledger for a subscription service that tracks two account balances:
- Usage balance: metered usage charges that remain unpaid (in cents).
- Subscription balance: recurring subscription fees that remain unpaid (in cents).
You'll implement a system that processes several types of operations:
Operations
Handler Operations (Stateful)
These operations maintain their own running state, initialized to the starting balances:
apply_charge: Takes an amount and adds it to the handler's usage balance. Returns the handler's current[subscription_balance, usage_balance].apply_credit: Takes an amount and applies it with priority rules: first reduce usage balance as much as possible, then apply any remainder to subscription balance. Returns the handler's current[subscription_balance, usage_balance].
Ledger Operations
These operations work with a separate ledger that tracks events by sequence number:
record: Takes[event_type, amount, sequence_number]whereevent_typeis"CHARGE"or"CREDIT". Inserts this event at its correct chronological position (sorted by sequence number) and recomputes the ledger's final state. Returns the ledger's current[subscription_balance, usage_balance]."CHARGE"events add to usage balance"CREDIT"events follow the same priority rules asapply_credit: pay down usage first, then subscription
current_balances: Returns the ledger's current[subscription_balance, usage_balance]after all recorded events.
Important Rules
- Handler state is independent from ledger state:
apply_chargeandapply_creditmaintain their own balances separately fromrecordandcurrent_balances. - Credit priority: Credits always reduce usage balance first. Only the amount remaining after usage reaches zero is applied to subscription balance.
- Charge behavior: Charges always add to usage balance only, never to subscription balance.
- Event ordering: Events in the ledger are always processed in ascending sequence number order, regardless of the order they're recorded.
- Balances can go negative: If a credit exceeds both balances, the subscription balance can become negative.
Function Signature
def process_ledger(operations: List[str], arguments: List[List[int]],
starting_usage_balance: int = 50000,
starting_subscription_balance: int = 0) -> List[List[int]]:
"""
Process a sequence of billing operations.
Args:
operations: List of operation names ("apply_charge", "apply_credit", "record", "current_balances")
arguments: List of arguments for each operation
- apply_charge: [amount]
- apply_credit: [amount]
- record: [event_type, amount, sequence_number] where event_type is "CHARGE" or "CREDIT"
- current_balances: []
starting_usage_balance: Initial usage balance (default 50000)
starting_subscription_balance: Initial subscription balance (default 0)
Returns:
List of [subscription_balance, usage_balance] for each operation
"""
Example
# Handler operations work independently
process_ledger(
["apply_charge", "apply_credit", "current_balances"],
[[200], [150], []],
1000, 0
)
# Returns: [[0, 1200], [0, 1050], [0, 1000]]
# - apply_charge: handler usage goes from 1000 → 1200
# - apply_credit: handler usage goes from 1200 → 1050
# - current_balances: ledger has no recorded events, returns starting balances [0, 1000]
# Ledger handles out-of-order events
process_ledger(
["record", "record", "current_balances", "record", "current_balances"],
[["CHARGE", 200, 10], ["CREDIT", 150, 20], [], ["CHARGE", 300, 5], []],
1000, 0
)
# Returns: [[0, 1200], [0, 1050], [0, 1050], [0, 1350], [0, 1350]]
# - After sequence 10: usage = 1000 + 200 = 1200
# - After sequence 20: usage = 1200 - 150 = 1050
# - Backdated to sequence 5: usage = 1000 + 300 + 200 - 150 = 1350
Constraints
- All amounts and balances are non-negative integers (cents)
- Sequence numbers are positive integers
- Up to 100,000 total operations
- Events may be recorded in any order relative to their sequence numbers
- Multiple events may share the same sequence number
Examples
Example 1
Input: process_ledger(['record', 'record', 'current_balances', 'record', 'current_balances'], [['CHARGE', 200, 10], ['CREDIT', 150, 20], [], ['CHARGE', 300, 5], []], 1000, 0)
Output: [[0, 1200], [0, 1050], [0, 1050], [0, 1350], [0, 1350]]
Example 2
Input: process_ledger(['apply_charge', 'apply_credit', 'current_balances'], [[200], [150], []], 1000, 0)
Output: [[0, 1200], [0, 1050], [0, 1000]]
Example 3
Input: process_ledger(['record', 'record', 'record', 'current_balances'], [['CHARGE', 100, 1], ['CREDIT', 150, 2], ['CHARGE', 50, 3], []], 100, 20)
Output: [[20, 200], [20, 50], [20, 100], [20, 100]]
Hints
Hint 1
Credits must reduce usage balance first; calculate the portion that applies to usage, then apply the remainder to subscription balance.
Hint 2
Handler operations maintain separate state from ledger operations—they don't interact with each other.
Hint 3
When inserting a backdated event in the ledger, find its position using binary search, then replay all events in sequence order to recompute the final state.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests two separate concerns wrapped in a unified interface:
Credit Waterfall Logic
The core business rule is payment priority. When a credit is applied, it must first pay down usage charges before touching subscription fees. Calculate how much credit applies to usage by taking the minimum of the credit amount and current usage balance, then subtract that from usage. Whatever remains from the credit amount reduces the subscription balance.
Charges are simpler: they unconditionally increase the usage balance.
Ordered Event Processing with Backdating
The ledger maintains two separate pieces of state:
- Handler state: tracks balances for
apply_chargeandapply_creditoperations, which modify state sequentially - Ledger state: tracks balances resulting from
recordoperations, which must be processed in sequence number order
When a record operation arrives, it may be backdated (have a sequence number earlier than previously recorded events). The implementation:
- Uses binary search to find the correct insertion position by sequence number
- Inserts the new event at that position
- Replays all events from the start in sequence order to recompute the final ledger balances
This ensures correctness: events are always applied in chronological order (by sequence number), regardless of when they were recorded.
Correctness
The separation of handler state from ledger state is critical. Handler operations (apply_charge, apply_credit) maintain running totals that carry forward from call to call, while ledger operations (record, current_balances) maintain a separate timeline of events sorted by sequence number.
The credit waterfall rule—usage first, then subscription—is applied consistently in both contexts through the shared apply_credit helper function.
Complexity
- Time: Each
apply_chargeandapply_creditoperation is O(1). Eachrecordoperation performs binary search O(log n), list insertion O(n), and full replay O(n), for O(n) total per record. Across all operations: O(k + mn) where k is handler operations, m is record operations, and n is average event count. - Space: O(n) to store recorded events.
For the given constraints (up to 100,000 operations), this approach is practical. An optimization would store intermediate balances and only recompute from the insertion point forward, but the current approach prioritizes simplicity and correctness.
from typing import List
from bisect import bisect_left
def process_ledger(operations: List[str], arguments: List[List[int]], starting_usage_balance: int = 50000, starting_subscription_balance: int = 0) -> List[List[int]]:
events = []
results = []
handler_subscription = starting_subscription_balance
handler_usage = starting_usage_balance
ledger_subscription = starting_subscription_balance
ledger_usage = starting_usage_balance
def apply_credit(subscription, usage, amount):
applied = min(usage, amount)
return subscription - (amount - applied), usage - applied
def apply_charge(subscription, usage, amount):
return subscription, usage + amount
for operation, args in zip(operations, arguments):
if operation == 'apply_credit':
handler_subscription, handler_usage = apply_credit(
handler_subscription, handler_usage, args[0]
)
results.append([handler_subscription, handler_usage])
elif operation == 'apply_charge':
handler_subscription, handler_usage = apply_charge(
handler_subscription, handler_usage, args[0]
)
results.append([handler_subscription, handler_usage])
elif operation == 'record':
kind, amount, sequence = args
index = bisect_left([event[0] for event in events], sequence)
events.insert(index, (sequence, kind, amount))
ledger_subscription = starting_subscription_balance
ledger_usage = starting_usage_balance
for _, event_kind, event_amount in events:
if event_kind == 'CHARGE':
ledger_subscription, ledger_usage = apply_charge(
ledger_subscription, ledger_usage, event_amount
)
elif event_kind == 'CREDIT':
ledger_subscription, ledger_usage = apply_credit(
ledger_subscription, ledger_usage, event_amount
)
results.append([ledger_subscription, ledger_usage])
elif operation == 'current_balances':
results.append([ledger_subscription, ledger_usage])
return results