KatInterview

Billing Ledger with Credit Prioritization and Backdating

Data Structure DesignAuto-graded · 23 test cases
MediumAuto-gradedData Structure Designdata-structuressimulationordered-data

Last 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] where event_type is "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 as apply_credit: pay down usage first, then subscription
  • current_balances: Returns the ledger's current [subscription_balance, usage_balance] after all recorded events.

Important Rules

  1. Handler state is independent from ledger state: apply_charge and apply_credit maintain their own balances separately from record and current_balances.
  2. Credit priority: Credits always reduce usage balance first. Only the amount remaining after usage reaches zero is applied to subscription balance.
  3. Charge behavior: Charges always add to usage balance only, never to subscription balance.
  4. Event ordering: Events in the ledger are always processed in ascending sequence number order, regardless of the order they're recorded.
  5. 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.