Backdated Loan Ledger with Fee-Priority Repayments

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Design an event-driven loan accounting ledger that tracks two integer balances per loan—principal_balance (initialized to 100000) and fee_balance (initialized to 0)—and expose it through the stream runner process_loan_events:

def process_loan_events(events: List[List]) -> List[List[List[int]]]:

Each incoming item in events has the form [event_type, amount, accounting_sequence], processed strictly in arrival order:

  1. Balance Allocation Rules (Balances, process_fee, process_payment)

    • "FEE": increases fee_balance by amount and leaves principal_balance unchanged.
    • "PAYMENT": pays down fee_balance first (up to min(amount, fee_balance) so fee_balance never becomes negative), then subtracts any leftover payment (amount - paid_to_fee) from principal_balance. When a payment exceeds fee_balance + principal_balance, principal_balance becomes negative to represent an overpayment credit.
  2. Out-of-Order Ledger (LoanLedger, LedgerEntry)

    • LoanLedger starts with self.balances = Balances(principal_balance=100000, fee_balance=0) and provides process_event(event_type, amount, accounting_sequence) -> List[LedgerEntry], where each LedgerEntry records (accounting_sequence, principal_balance, fee_balance) immediately after that event takes effect.
    • Events can arrive out of chronological sequence (for instance, a backdated fee arriving after later payments).
    • Entries in the returned history must be ordered by ascending accounting_sequence. When multiple events share the same accounting_sequence, keep them in arrival order (newly received events follow earlier arrivals at that sequence).
    • Avoid recomputing the entire loan from scratch on every arrival: preserve unaffected earlier snapshots and replay only from the newly inserted event's position onward. Keep self.balances equal to the state at the end of the timeline (highest sequence).
    • Validate inputs before mutating ledger state: if event_type is neither "PAYMENT" nor "FEE", if amount is negative or not an int (rejecting bool), or if accounting_sequence is not an int (rejecting bool), raise ValueError with existing state intact.
  3. Stream Output

    • process_loan_events(events) feeds each event into a single LoanLedger instance and collects the resulting history after every step, serializing each LedgerEntry as [accounting_sequence, principal_balance, fee_balance].

Examples

Example 1

Input:
  events = [["PAYMENT", 2000, 2], ["PAYMENT", 800, 6], ["FEE", 250, 4]]

Output:
  [
    [[2, 98000, 0]],
    [[2, 98000, 0], [6, 97200, 0]],
    [[2, 98000, 0], [4, 98000, 250], [6, 97450, 0]]
  ]

Explanation: - First arrival (PAYMENT 2000 at sequence 2): reduces principal from 100000 to 98000, giving [[2, 98000, 0]]. - Second arrival (PAYMENT 800 at sequence 6): reduces principal further to 97200, giving [[2, 98000, 0], [6, 97200, 0]]. - Third arrival (FEE 250 at sequence 4): slots in between sequences 2 and 6. Sequence 2 stays (98000, 0) without replay; sequence 4 becomes (98000, 250); replaying sequence 6's 800 payment now clears the 250 fee first and applies only 550 toward principal (98000 - 550 = 97450), producing [6, 97450, 0].

Example 2

Input:
  events = [["FEE", 400, 5], ["PAYMENT", 150, 5], ["PAYMENT", 600, 1]]

Output:
  [
    [[5, 100000, 400]],
    [[5, 100000, 400], [5, 100000, 250]],
    [[1, 99400, 0], [5, 99400, 400], [5, 99400, 250]]
  ]

Explanation: - First arrival posts a 400 fee at sequence 5 ((100000, 400)). - Second arrival ties at sequence 5, so it lands after the fee and partially reduces fee_balance to 250 while principal remains 100000. - Third arrival is backdated to sequence 1 (before everything else), lowering initial principal to 99400 and shifting the principal balance of both sequence-5 snapshots to 99400.

Constraints

  • Starting loan balances are principal_balance = 100000 and fee_balance = 0.
  • 0 <= len(events) <= 2000.
  • Valid events have event_type in {"PAYMENT", "FEE"}, integer amount >= 0 (not isinstance(amount, bool)), and integer accounting_sequence (not isinstance(accounting_sequence, bool)); invalid inputs raise ValueError.

Step-by-step walkthrough

  1. Understand the loan rules and settle open edge cases

    A loan starts with principal_balance = 100000 and fee_balance = 0. Two kinds of events arrive over time:

    • FEE (amount): adds amount to fee_balance and leaves principal_balance unchanged.
    • PAYMENT (amount): pays down fee_balance first, and applies any leftover money to principal_balance:
    Incoming PAYMENT
          |
          v
    [ 1. Pay down fee_balance (up to min(amount, fee_balance)) ]
          |
          v  (any remaining amount = amount - paid_to_fee)
    [ 2. Reduce principal_balance ]
    

    In LoanLedger, events carry an integer accounting_sequence (acting as their effective timeline position) and can arrive out of order. After each arrival, we return the full ledger history sorted by accounting_sequence.

    Let's state clear, consistent answers to the prompt's clarifying questions up front:

    • Partial fee payments: if amount < fee_balance, the entire payment reduces fee_balance and principal_balance stays untouched.
    • Overpayments: if a payment exceeds fee_balance + principal_balance, principal_balance goes negative (representing a credit owed to the borrower) so no money ever vanishes silently and principal + fee always equals 100000 + total_fees - total_payments.
    • Amounts and validation: amounts must be non-negative integers (0 or positive, like cents). Negative amounts, booleans, or unknown event types raise ValueError without changing the ledger.
    • Ties on accounting_sequence: events with the same sequence are ordered in arrival order (a newly arrived event goes after earlier arrivals at that sequence).
    • self.balances: always holds the balances after the final entry on the accounting timeline (self.states[-1]), not the middle-of-history entry of a backdated event.
  2. Part 1: Write immutable balance handlers

    Let's trace both payment cases with fee_balance = 300 and principal_balance = 100000:

    • Payment of 100 (smaller than fee): paid_to_fee = min(100, 300) = 100, paid_to_principal = 100 - 100 = 0 -> (100000, 200).
    • Payment of 1000 (larger than fee): paid_to_fee = min(1000, 300) = 300, paid_to_principal = 1000 - 300 = 700 -> (99300, 0).

    Notice one formula handles both cases cleanly: paid_to_fee = min(amount, balances.fee_balance), and paid_to_principal = amount - paid_to_fee.

    Just as important: process_payment and process_fee return a brand-new Balances instance instead of mutating balances in place. In Part 2 we store the Balances snapshot after every historical event; marking @dataclass(frozen=True) guarantees a replay of event 3 can never accidentally overwrite the saved snapshot of event 2.

    from dataclasses import dataclass
    
    INITIAL_PRINCIPAL = 100000
    EVENT_TYPES = ("PAYMENT", "FEE")
    
    
    # frozen=True makes snapshots immutable so replaying later events can never overwrite saved past states.
    @dataclass(frozen=True)
    class Balances:
        principal_balance: int
        fee_balance: int
    
    
    @dataclass(frozen=True)
    class LedgerEntry:
        accounting_sequence: int
        principal_balance: int
        fee_balance: int
    
    
    def check_amount(amount: int) -> None:
        # Reject booleans explicitly because `bool` is a subclass of `int` in Python.
        if isinstance(amount, bool) or not isinstance(amount, int) or amount < 0:
            raise ValueError(f"amount must be a non-negative integer, got {amount!r}")
    
    
    def check_sequence(accounting_sequence: int) -> None:
        if isinstance(accounting_sequence, bool) or not isinstance(accounting_sequence, int):
            raise ValueError(f"accounting_sequence must be an integer, got {accounting_sequence!r}")
    
    
    def process_payment(balances: Balances, amount: int) -> Balances:
        check_amount(amount)
        paid_to_fee = min(amount, balances.fee_balance)
        paid_to_principal = amount - paid_to_fee
        return Balances(
            principal_balance=balances.principal_balance - paid_to_principal,
            fee_balance=balances.fee_balance - paid_to_fee,
        )
    
    
    def process_fee(balances: Balances, amount: int) -> Balances:
        check_amount(amount)
        return Balances(
            principal_balance=balances.principal_balance,
            fee_balance=balances.fee_balance + amount,
        )
    
  3. Why backdated events change later entries — but never earlier ones

    Look at Example 1 when FEE 250 at sequence 4 arrives after PAYMENT 2000 (seq 2) and PAYMENT 800 (seq 6):

    Before FEE arrives:
      init (100000, 0) --[PAY 2000 @ seq 2]--> (98000, 0) --[PAY 800 @ seq 6]--> (97200, 0)
    
    After FEE 250 @ seq 4 is inserted in the middle:
      init (100000, 0) --[PAY 2000 @ seq 2]--> (98000, 0) --[FEE 250 @ seq 4]--> (98000, 250) --[PAY 800 @ seq 6]--> (97450, 0)
                                                   ^                                                                      ^
                                            UNCHANGED prefix!                                              250 went to fee, only 550 to principal!
    

    Two key observations jump out from this timeline:

    1. You cannot just apply a backdated fee to self.balances. Because sequence 4 happened before sequence 6, PAYMENT 800 at sequence 6 must now absorb that 250 fee first, changing sequence 6's entry from (97200, 0) to (97450, 0).
    2. You do NOT need to replay from the start of the loan. Nothing before sequence 4 changed! As long as we saved the post-event snapshot (98000, 0) at sequence 2, we can start straight from (98000, 0) and replay only from sequence 4 onward.
  4. Key idea: three parallel lists and binary search (`bisect_right`)

    Inside LoanLedger, we maintain three parallel lists kept sorted by accounting_sequence:

    index i:          0                   1                   2
    sequences:  [     2,                  4,                  6            ]
    events:     [ ("PAYMENT", 2000),  ("FEE", 250),       ("PAYMENT", 800) ]
    states:     [ Balances(98000,0),  Balances(98000,250), Balances(97450,0) ]
    

    When a new event with accounting_sequence arrives:

    • We locate its insertion index position = bisect.bisect_right(self.sequences, accounting_sequence) in O(log n) time.
    • Why bisect_right instead of bisect_left? When accounting_sequence ties with existing entries, bisect_right places the new event to the right of (after) all earlier arrivals at that sequence, preserving arrival order on ties.
    • We insert into sequences, events, and states at position, then call self._replay_from(position).
  5. Implement `LoanLedger.process_event`

    Always validate event_type, amount, and accounting_sequence before inserting into any list. If we inserted into self.sequences first and then raised ValueError on a negative amount, our three parallel lists would have different lengths and corrupt every future call.

    import bisect
    from typing import List, Tuple
    
    
    class LoanLedger:
        def __init__(self):
            self.balances = Balances(principal_balance=INITIAL_PRINCIPAL, fee_balance=0)
            self.sequences: List[int] = []
            self.events: List[Tuple[str, int]] = []
            self.states: List[Balances] = []
    
        def process_event(
            self, event_type: str, amount: int, accounting_sequence: int
        ) -> List[LedgerEntry]:
            # Phase 1: validate every input BEFORE mutating any list so bad calls leave no partial state.
            if event_type not in EVENT_TYPES:
                raise ValueError(f"unknown event type: {event_type!r}")
            check_amount(amount)
            check_sequence(accounting_sequence)
    
            # Phase 2: find insertion slot; bisect_right places equal-sequence ties AFTER older arrivals.
            position = bisect.bisect_right(self.sequences, accounting_sequence)
            self.sequences.insert(position, accounting_sequence)
            self.events.insert(position, (event_type, amount))
            self.states.insert(position, Balances(INITIAL_PRINCIPAL, 0))
    
            # Phase 3: recompute only from `position` onward, keeping all earlier snapshots untouched.
            self._replay_from(position)
    
            # Current loan balances reflect the end of the accounting timeline (highest sequence).
            self.balances = self.states[-1]
            return self.history()
    
  6. Implement suffix replay, history export, and the judge wrapper

    _replay_from(position) grabs the starting state right before position:

    • If position == 0 (the new event precedes every existing event), start from Balances(100000, 0).
    • Otherwise, start from self.states[position - 1].

    Then a simple loop from position to len(self.events) - 1 applies each (event_type, amount) and overwrites self.states[i]. If an in-order event lands at the very end (position == n - 1), this loop runs just one iteration!

    def _replay_from(self, position: int) -> None:
        if position == 0:
            state = Balances(principal_balance=INITIAL_PRINCIPAL, fee_balance=0)
        else:
            state = self.states[position - 1]
    
        for i in range(position, len(self.events)):
            event_type, amount = self.events[i]
            state = apply_event(state, event_type, amount)
            self.states[i] = state
    

    Finally, history() zips sequences and states into LedgerEntry objects, and process_loan_events(events) feeds the input stream into LoanLedger and formats each LedgerEntry as [sequence, principal, fee] for the automated judge.

  7. Trace Example 1 event by event

    Arrival 1: ("PAYMENT", 2000, seq=2)
      bisect_right([], 2) -> position = 0 (start from (100000, 0))
      replay i=0: PAY 2000 -> (98000, 0)
      sequences = [2]
      states    = [(98000, 0)]
      returns   -> [[2, 98000, 0]]
    
    Arrival 2: ("PAYMENT", 800, seq=6)
      bisect_right([2], 6) -> position = 1 (start from states[0] = (98000, 0))
      replay i=1: PAY 800 -> (97200, 0)         (i=0 was NOT reprocessed!)
      sequences = [2, 6]
      states    = [(98000, 0), (97200, 0)]
      returns   -> [[2, 98000, 0], [6, 97200, 0]]
    
    Arrival 3: ("FEE", 250, seq=4)
      bisect_right([2, 6], 4) -> position = 1 (start from states[0] = (98000, 0))
      replay i=1: FEE 250 -> (98000, 250)
      replay i=2: PAY 800 -> 250 to fee, 550 to principal -> (97450, 0)
      sequences = [2, 4, 6]
      states    = [(98000, 0), (98000, 250), (97450, 0)]
      returns   -> [[2, 98000, 0], [4, 98000, 250], [6, 97450, 0]]
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import bisect
    from dataclasses import dataclass
    
    INITIAL_PRINCIPAL = 100000
    EVENT_TYPES = ("PAYMENT", "FEE")
    
    
    # frozen=True makes snapshots immutable so replaying later events can never overwrite saved past states.
    @dataclass(frozen=True)
    class Balances:
        principal_balance: int
        fee_balance: int
    
    
    @dataclass(frozen=True)
    class LedgerEntry:
        accounting_sequence: int
        principal_balance: int
        fee_balance: int
    
    
    def check_amount(amount: int) -> None:
        # Reject booleans explicitly because `bool` is a subclass of `int` in Python.
        if isinstance(amount, bool) or not isinstance(amount, int) or amount < 0:
            raise ValueError(f"amount must be a non-negative integer, got {amount!r}")
    
    
    def check_sequence(accounting_sequence: int) -> None:
        if isinstance(accounting_sequence, bool) or not isinstance(accounting_sequence, int):
            raise ValueError(f"accounting_sequence must be an integer, got {accounting_sequence!r}")
    
    
    def process_payment(balances: Balances, amount: int) -> Balances:
        check_amount(amount)
        # Pay down fees first; fees can never drop below 0 because we cap at balances.fee_balance.
        paid_to_fee = min(amount, balances.fee_balance)
        # Any leftover payment reduces principal (negative principal represents an overpayment credit).
        paid_to_principal = amount - paid_to_fee
        return Balances(
            principal_balance=balances.principal_balance - paid_to_principal,
            fee_balance=balances.fee_balance - paid_to_fee,
        )
    
    
    def process_fee(balances: Balances, amount: int) -> Balances:
        check_amount(amount)
        return Balances(
            principal_balance=balances.principal_balance,
            fee_balance=balances.fee_balance + amount,
        )
    
    
    def apply_event(balances: Balances, event_type: str, amount: int) -> Balances:
        if event_type == "PAYMENT":
            return process_payment(balances, amount)
        if event_type == "FEE":
            return process_fee(balances, amount)
        raise ValueError(f"unknown event type: {event_type!r}")
    
    
    class LoanLedger:
        def __init__(self):
            self.balances = Balances(principal_balance=INITIAL_PRINCIPAL, fee_balance=0)
            # Three parallel lists kept sorted by accounting_sequence (ties stay in arrival order):
            # - sequences[i]: int accounting_sequence of entry i, e.g. [1, 2, 3]
            # - events[i]:    (event_type, amount) tuple of entry i, e.g. [("PAYMENT", 1000), ...]
            # - states[i]:    Balances snapshot right AFTER entry i is applied
            self.sequences: List[int] = []
            self.events: List[Tuple[str, int]] = []
            self.states: List[Balances] = []
    
        def process_event(
            self, event_type: str, amount: int, accounting_sequence: int
        ) -> List[LedgerEntry]:
            # Phase 1: validate every input BEFORE mutating any list so bad calls leave no partial state.
            if event_type not in EVENT_TYPES:
                raise ValueError(f"unknown event type: {event_type!r}")
            check_amount(amount)
            check_sequence(accounting_sequence)
    
            # Phase 2: find insertion slot; bisect_right places equal-sequence ties AFTER older arrivals.
            position = bisect.bisect_right(self.sequences, accounting_sequence)
            self.sequences.insert(position, accounting_sequence)
            self.events.insert(position, (event_type, amount))
            self.states.insert(position, Balances(INITIAL_PRINCIPAL, 0))
    
            # Phase 3: recompute only from `position` onward, keeping all earlier snapshots untouched.
            self._replay_from(position)
    
            # Current loan balances reflect the end of the accounting timeline (highest sequence).
            self.balances = self.states[-1]
            return self.history()
    
        def _replay_from(self, position: int) -> None:
            # Events before `position` never changed, so resume from the snapshot right before `position`.
            if position == 0:
                state = Balances(principal_balance=INITIAL_PRINCIPAL, fee_balance=0)
            else:
                state = self.states[position - 1]
    
            for i in range(position, len(self.events)):
                event_type, amount = self.events[i]
                state = apply_event(state, event_type, amount)
                self.states[i] = state
    
        def history(self) -> List[LedgerEntry]:
            entries = []
            for i in range(len(self.sequences)):
                state = self.states[i]
                entries.append(
                    LedgerEntry(
                        accounting_sequence=self.sequences[i],
                        principal_balance=state.principal_balance,
                        fee_balance=state.fee_balance,
                    )
                )
            return entries
    
    
    def process_loan_events(events: List[List]) -> List[List[List[int]]]:
        ledger = LoanLedger()
        outputs = []
    
        # Feed events in arrival order and serialize each returned history for the judge.
        for event_type, amount, accounting_sequence in events:
            entries = ledger.process_event(event_type, amount, accounting_sequence)
            rows = []
            for entry in entries:
                rows.append(
                    [entry.accounting_sequence, entry.principal_balance, entry.fee_balance]
                )
            outputs.append(rows)
    
        return outputs
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a loan as two buckets sitting in a line: a small fee bucket in front (starting at 0) and a large principal bucket behind it (starting at 100000). Every FEE pours money into the front bucket, while every PAYMENT scoops as much as possible out of the front fee bucket first and only uses leftover money to lower the back principal bucket. Now think of the ledger as a dated checkbook register where every line saves the balance snapshot right after that transaction: if a late Tuesday fee arrives in the mail on Thursday, Monday's line cannot change, so you read Monday's saved snapshot, insert Tuesday's fee right after Monday, and recalculate only Tuesday through Thursday.

Why do simpler shortcuts fail? If you maintain only a single live self.balances object without history, adding a late fee of 100 after two payments leaves fee = 100 at the end, missing the fact that the later payment would have paid off that 100 fee instead of reducing principal! On the flip side, re-sorting the entire log and replaying from (100000, 0) on every call wastes work recalculating thousands of untouched prefix events whenever an event arrives near the end of the timeline.

Let's walk through Example 1 (PAYMENT 2000 at seq 2, PAYMENT 800 at seq 6, then a backdated FEE 250 at seq 4):

1. PAY 2000 @ seq 2 -> start (100000, 0) -> [(2, 98000, 0)]
2. PAY  800 @ seq 6 -> resume from seq 2's (98000, 0) -> [(2, 98000, 0), (6, 97200, 0)]
3. FEE  250 @ seq 4 -> insert at index 1; seq 2 stays (98000, 0) untouched!
                       - apply FEE 250 at seq 4 -> (98000, 250)
                       - replay PAY 800 at seq 6 -> 250 clears fee, 550 lowers principal -> (97450, 0)
                    -> [(2, 98000, 0), (4, 98000, 250), (6, 97450, 0)]

Complexity

Let n be the number of events stored in the ledger after the current call, and k (1 <= k <= n) be the number of entries at or after the new event's insertion position (k = 1 for an in-order arrival at the tail; k = n for a backdated arrival before everything else).

  • State update per process_event call: O(log n + k). Binary search (bisect_right, which repeatedly halves the sorted sequences list to locate the insertion point) takes O(log n) comparisons. Inserting into the three Python lists shifts k - 1 trailing elements in O(k) time, and _replay_from runs O(1) arithmetic for each of the k affected events (O(1) replay work when events arrive in order!).
  • History return per process_event call: O(n) (making total process_loan_events runtime O(n^2) across n calls). Because the required API returns a fresh n-entry history list on every call, constructing that output list costs O(n) per call and 1 + 2 + ... + n = O(n^2) total output entries across n events. If the API returned only self.balances or the k modified suffix entries, each call would take O(log n + k).
  • Ledger space: O(n). Apart from the returned output lists, LoanLedger stores one integer in sequences, one (event_type, amount) tuple in events, and one immutable Balances snapshot in states per event.

Edge cases

  • Payment smaller than or equal to current fee balance: paid_to_fee = min(amount, fee_balance) absorbs the entire payment into fees (paid_to_principal = 0), leaving principal_balance unchanged and never letting fee_balance go negative.
  • Overpayment (amount > fee_balance + principal_balance): Fees drop to 0 and principal_balance becomes negative (for example, -100), cleanly recording a borrower credit while preserving principal + fee == 100000 + fees - payments.
  • Backdated event earlier than all existing events (position == 0): _replay_from(0) starts from Balances(100000, 0) instead of self.states[-1] (which in Python would accidentally read the last element of self.states if we wrote self.states[position - 1] without checking position == 0!).
  • Ties on accounting_sequence: bisect_right places a later-arriving event after all earlier arrivals sharing that sequence, so FEE 100 @ seq 5 followed by PAYMENT 50 @ seq 5 ends at fee 50, whereas the reverse arrival order ends at fee 100.
  • Invalid inputs (amount < 0, amount = True, unknown event_type): Validation runs before any .insert(...) call, raising ValueError while leaving sequences, events, states, and self.balances completely intact.

Common mistakes

  • Mutating Balances in place instead of returning a new Balances object: If process_payment modifies balances.principal_balance -= ... on a mutable object, multiple slots in self.states can end up aliasing or corrupting earlier historical snapshots during replay.
  • Forgetting if position == 0: in _replay_from: Writing state = self.states[position - 1] unconditionally evaluates self.states[-1] when position == 0, starting the loan from its final state instead of (100000, 0)!
  • Using bisect_left instead of bisect_right: bisect_left inserts a tied sequence before older arrivals at the same sequence, reversing arrival order on same-day events.
  • Setting self.balances to the newly inserted event's state: When a backdated event is inserted at index 1 of a 10-event ledger, self.balances must equal self.states[-1] (index 9 after replay), not self.states[1].
  • Inserting into self.sequences before validating amount: If check_amount then raises ValueError, self.sequences has one extra element compared to self.events and self.states, breaking every future call.

Alternative approaches

  • Append and sort-and-replay from scratch on every event: Store (sequence, arrival_index, event_type, amount), sort all n events in O(n log n), and replay all n events from (100000, 0). Too wasteful for production streams because in-order events still reprocess the entire loan history, but unbeatable as a 15-line brute-force test oracle.
  • Periodic checkpoints (states saved every B events): Instead of storing a Balances snapshot on every single event, store one snapshot every B events (a checkpoint). Memory for snapshots drops by a factor of B, while a backdated event at position steps back at most B events to the nearest earlier checkpoint before replaying forward.

Follow-up questions

  • Suppose callers only queried the latest balances—or balances at one target sequence—instead of requesting the entire history every time; how could you insert backdated transactions in O(log n) time without replaying later entries? Write each event as a signed number x (+amount for FEE, -amount for PAYMENT) and consider the prefix sums S_0 = 0, S_1, ..., S_j (where S_j is the cumulative sum of the first j signed events). Every event changes principal + fee by x, while fee follows fee_j = max(0, fee_{j-1} + x_j) because fees cannot drop below zero; by induction, the deepest cumulative dip M_j = min(S_0, S_1, ..., S_j) is the exact total amount ever absorbed by principal, giving principal_j = 100000 + M_j and fee_j = S_j - M_j! By storing events in a balanced binary search tree (a self-balancing tree like a treap, keyed by (sequence, arrival_order)) where each subtree caches (subtree_sum, min_prefix_sum) merged via (L_sum + R_sum, min(L_min, L_sum + R_min)), both out-of-order insertions and as-of balance queries run in O(log n) time with zero suffix replay.
  • How would you design support for voiding a historical transaction—like waiving an old fee or reversing a dishonored payment—while preserving an audit log and fixing downstream balances? Assign each event a unique event_id and store an index event_id -> ledger_entry. To reverse an event while preserving an audit trail (a permanent record showing both the original transaction and its cancellation for accounting compliance), mark the original event at its original accounting_sequence as reversed (so _replay_from treats its effective amount as 0, or insert a zero-effect reversal marker linked to it) and call _replay_from from that original position. Crucially, you cannot reverse a past PAYMENT 300 simply by appending a new FEE 300 today: after FEE 100 then PAYMENT 300, balances are (99800, 0); undoing the payment at its original position restores (100000, 100), whereas posting a new FEE 300 leaves (99800, 300) — the wrong split between principal and fee!
  • When an upstream message broker retries and delivers duplicate events, how do you guarantee idempotent processing? Making an operation idempotent (meaning processing the exact same request once or several times produces the exact same ledger state) requires the caller to attach a unique idempotency key event_id to each event, since two legitimate payments of 50 on the same sequence look identical without an ID. Store a dictionary seen_events[event_id] = (event_type, amount, accounting_sequence): if event_id has not been seen, process the event and record its payload; if event_id was already seen with the same payload, skip mutation and return self.history(); if it arrives with a different payload, raise ValueError to flag a producer bug. In a database-backed service, write the seen_events row and the ledger update inside the same atomic database transaction so a crash mid-request can never double-apply a payment on retry.

Follow-up questions

Similar questions

More Valon interview questions

All 8 Valon questions →