Out-of-Order Loan Event Ledger with Fee-First Payments
Data Structure DesignAuto-graded · 19 test casesLast updated
Tests ordered insertion, fee-before-principal payment allocation, and efficient forward-propagation of balance changes when events arrive out of sequence.
Out-of-Order Loan Event Ledger with Fee-First Payments
You are building a simplified loan accounting system that tracks a loan's balance history as events stream in — potentially out of chronological order.
Loan State
A loan begins with:
- Principal balance:
100000 - Fee balance:
0
Event Types
Each event is described by three values: an event type ("PAYMENT" or "FEE"), a positive integer amount, and an integer accounting_sequence that defines where the event belongs in the official ledger order.
- A
"FEE"event increases the fee balance by the given amount. - A
"PAYMENT"event first reduces the fee balance as much as possible, then applies any remainder to the principal balance.
Task
Given a list of events, process them one at a time in the order they appear in the input list. After each event is processed, produce a snapshot of the full ledger history sorted by accounting_sequence.
Each entry in the history is a three-element list [accounting_sequence, principal_balance, fee_balance] representing the loan state immediately after that event's effect.
Return a list of these snapshots — one snapshot per event, in input order.
Key Details
- Events may arrive with an
accounting_sequencethat places them before already-processed events. When this happens, all subsequent ledger entries must be recomputed to reflect the insertion. - When two events share the same
accounting_sequence, the one received later in the input is placed after the earlier-received one (stable / append-to-right tie-breaking viabisect_right). self.balances(if you model this as a class) should always reflect the state at the end of the highest-sequence entry.- Balances may go negative if a payment exceeds the remaining principal after fees are cleared.
Constraints
1 <= len(events) <= 1000- Each event is
[event_type, amount, accounting_sequence] event_typeis either"PAYMENT"or"FEE"1 <= amount <= 10^91 <= accounting_sequence <= 10^9- All values are integers except
event_type
Examples
Example 1
Input: process_loan_events([['PAYMENT', 1000, 1], ['PAYMENT', 500, 3], ['FEE', 100, 2]])
Output: [[[1, 99000, 0]], [[1, 99000, 0], [3, 98500, 0]], [[1, 99000, 0], [2, 99000, 100], [3, 98600, 0]]]
Example 2
Input: process_loan_events([['FEE', 100, 2], ['PAYMENT', 1000, 1]])
Output: [[[2, 100000, 100]], [[1, 99000, 0], [2, 99000, 100]]]
Hints
Hint 1
Use binary search on a sorted list of accounting sequences to find the correct insertion index for each incoming event. Python's bisect module makes this straightforward.
Hint 2
Once you insert the new event at index i, you only need to recompute balances for entries at index i and beyond — entries before i are unaffected. Start the forward pass from the state stored at index i-1 (or the initial loan state if i is 0).
Hint 3
After the forward pass, the final entry in the sorted list holds the loan state at the highest accounting sequence. That is the value to store as the current balances.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Idea
The key insight is that events must appear in the ledger sorted by accounting_sequence, but they arrive in arbitrary input order. This means each new event may need to be inserted somewhere in the middle of the existing history, and every entry after it depends on the running balance, so those entries must be updated.
Two structural choices make this efficient:
-
Binary search for insertion — keep a parallel list of sequence numbers and use
bisect_rightto find the correct index in O(log n).bisect_rightplaces a duplicate sequence after all existing entries with the same value, which is the tie-breaking rule specified. -
Forward propagation from the insertion point — entries before the insertion index are completely unaffected. Only entries from the insertion index onward need to be recomputed. Start from the state stored at
index - 1(or the initial loan state when inserting at position 0) and replay forward.
Why It Is Correct
- The
sequences,ordered, andstateslists are always kept in sync and sorted byaccounting_sequence. - After inserting at position
index, the balance atindex - 1is already correct (it was not touched). Replaying from there guarantees each subsequent state is the exact result of applying all prior events in ledger order. bisect_rightensures that when two events share a sequence number, the one that arrived later is placed to the right — consistent, deterministic, and matching the expected outputs.- Payments that exceed the combined fee and principal produce a negative principal, which is the specified behavior (no capping or rejection).
Complexity
Let n be the total number of events processed so far and k be the number of entries after the insertion point (i.e., how far back the new event lands).
| Step | Cost |
|---|---|
| Binary search | O(log n) |
| List insert (shift) | O(n) |
| Forward propagation | O(k) |
| Building the result snapshot | O(n) |
Per call: O(n) time in the worst case (insert at position 0, or building the snapshot). Space is O(n) for the three parallel lists.
In practice, if backdated events are rare and land close to the end, the propagation step is cheap (small k). The dominant cost is then the O(n) snapshot construction.
Full Reference Solution
from bisect import bisect_right
from typing import List
def process_loan_events(events: List[List]) -> List[List[List[int]]]:
ordered = [] # events sorted by accounting_sequence
sequences = [] # parallel list of just the sequences, for bisect
states = [] # parallel list of (principal, fee) after each event
results = []
for event_type, amount, sequence in events:
# Find insertion index using bisect_right for stable tie-breaking
index = bisect_right(sequences, sequence)
sequences.insert(index, sequence)
ordered.insert(index, (event_type, amount, sequence))
states.insert(index, None) # placeholder; will be filled below
# Starting balances for the forward pass
if index > 0:
principal, fee = states[index - 1]
else:
principal, fee = 100000, 0
# Recompute every entry from the insertion point forward
for i in range(index, len(ordered)):
kind, value, _ = ordered[i]
if kind == "FEE":
fee += value
else:
# Pay fees first, then apply remainder to principal
paid_fee = min(fee, value)
fee -= paid_fee
principal -= value - paid_fee
states[i] = (principal, fee)
# Build the snapshot for this call
results.append(
[[seq, p, f] for seq, (p, f) in zip(sequences, states)]
)
return results