Out-of-Order Loan Ledger
Problem statement
A loan starts with initialPrincipal and a zero fee balance. Process events in receive order. Each event has a unique accounting sequence:
FEEadds its amount to the fee balance.PAYMENTpays the fee balance first and then principal. Any amount remaining after both balances reach zero is ignored.
Events may arrive out of accounting order. After inserting each received event, order all events by accounting sequence and recompute the balances from the earliest affected position.
Return one ledger snapshot after every received event. A snapshot lists all current entries in ascending accounting-sequence order as sequence:principalBalance:feeBalance, joined with |.
Function
processLoanEvents(initialPrincipal: long, eventTypes: String[], amounts: long[], sequences: int[]) → String[]Examples
Example 1
initialPrincipal = 100000eventTypes = ["PAYMENT","PAYMENT","FEE"]amounts = [1000,500,100]sequences = [1,3,2]return = ["1:99000:0","1:99000:0|3:98500:0","1:99000:0|2:99000:100|3:98600:0"]When sequence 2 arrives, only the affected suffix is recomputed, and the later payment clears its fee before principal.
Example 2
initialPrincipal = 1000eventTypes = ["FEE","PAYMENT"]amounts = [75,100]sequences = [10,20]return = ["10:1000:75","10:1000:75|20:975:0"]The payment clears 75 of fees and then reduces principal by 25.
Example 3
initialPrincipal = 50eventTypes = ["PAYMENT"]amounts = [80]sequences = [1]return = ["1:0:0"]Balances do not become negative.
Constraints
0 <= initialPrincipal <= 10^9.eventTypes.length == amounts.length == sequences.length <= 100000.- Every type is
FEEorPAYMENT. 0 <= amounts[i] <= 10^9.- Accounting sequences are unique signed 32-bit integers.
- All running balances fit in a signed 64-bit integer.