Ledger Replay Cleanup: Apply Each Payment Event Once
Arrays & HashingAuto-graded · 19 test casesLast updated
Process a stream of possibly redelivered payment events and compute final account balances by applying each unique event ID only once.
Ledger Replay Cleanup
A payments service receives events from a message broker that guarantees every event arrives at least once. Occasionally a worker crashes before confirming an event, so the same event is delivered again. Your job is to rebuild account balances from the stream so that no event is counted more than once.
Task
Write a function that takes the starting balances and the list of received events, and returns the final balance of every account.
Input
starting_balances: a dictionary mapping an account name (string) to its integer starting balance.events: a list of events, in the order they were received. Each event is a list of three items:[event_id, account, amount].event_idis a string identifying the event.accountis a string naming the account to change.amountis an integer to add to that account's balance. A negative amount is a debit and zero is allowed.
Rules
- Process events in the given order.
- The first time an
event_idappears, add itsamountto the balance of itsaccount. - If an
event_idhas already been seen, ignore the event completely. This holds even if the repeat names a different account or amount. The first occurrence always wins, and uniqueness of IDs is global across all accounts. - An account that is not in
starting_balancesstarts at 0 when it first receives an applied event. - Accounts in
starting_balancesmust appear in the result even if no event touches them. - Do not modify the input dictionary. Return a new dictionary.
- If
eventsis empty, return a copy ofstarting_balances.
Output
A dictionary mapping each account name to its final integer balance.
Constraints
- Account names and event IDs are strings.
- Amounts and balances are integers (positive, negative, or zero).
- The number of events can be large, so aim for a solution that runs in linear time in the number of events.
- Each event list has exactly three elements.
Examples
Example 1
Input: rebuild_balances_once({}, [['tx1', 'alice', 100], ['tx1', 'alice', 100], ['tx2', 'alice', -30]])
Output: {'alice': 70}
Example 2
Input: rebuild_balances_once({'alice': 50, 'bob': 20}, [['a', 'alice', 10], ['b', 'bob', -5], ['a', 'alice', 10], ['c', 'alice', 7]])
Output: {'alice': 67, 'bob': 15}
Example 3
Input: rebuild_balances_once({'alice': 0}, [['t1', 'alice', 100], ['t2', 'alice', 25], ['t1', 'alice', 100], ['t2', 'alice', 25]])
Output: {'alice': 125}
Hints
Hint 1
You need a fast way to ask whether an event ID has already been handled. Which built-in structure gives average O(1) membership checks?
Hint 2
Start from a copy of the starting balances so the caller's dictionary is untouched, and use a default of 0 for accounts you have not seen before.
Hint 3
Mark the event ID as seen only when you apply it, and skip any later event with an ID already in your seen collection, regardless of its account or amount.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because delivery is at-least-once, the same event can show up several times, and adding an amount is not safe to repeat. The fix is to make the update idempotent by remembering which event IDs have already been applied.
- Copy the starting balances into a new dictionary.
- Keep a set of event IDs that have been applied.
- Walk through the events in order. If the ID is already in the set, skip the event. Otherwise add the ID to the set and add the amount to the account's balance, treating a missing account as 0.
- Return the dictionary.
Why it is correct
A redelivered event carries the same ID as the original. The first arrival records the ID and applies the amount. Every later arrival finds the ID in the set and is skipped, so each distinct ID changes a balance exactly once. Since the first occurrence is the one applied, repeats with a different account or amount are ignored, as the rules require. Negative and zero amounts are handled by ordinary addition. Copying the input means the caller's data is not changed, and an empty event list simply returns the copy.
In a real system, recording the ID and updating the balance must happen atomically (for example in one database transaction with a unique constraint on the ID), otherwise a crash between the two steps could lose or duplicate an update.
Complexity
With n events, each step does a set lookup, a set insert, and a dictionary update, all O(1) on average.
- Time: O(n)
- Space: O(a + k), where a is the number of accounts and k is the number of distinct event IDs.
Reference solution
from typing import Dict, List
def rebuild_balances_once(starting_balances: Dict[str, int], events: List[List[object]]) -> Dict[str, int]:
# Copy so the caller's dictionary is not changed.
balances = dict(starting_balances)
# Event IDs that have already been applied.
seen = set()
for event_id, account, amount in events:
if event_id in seen:
# Redelivered event: ignore.
continue
seen.add(event_id)
balances[account] = balances.get(account, 0) + amount
return balances