Reconcile Ledger and Bank Snapshots for a Month
SQL & DataAuto-graded · 19 test casesLast updated
Join two per-month balance datasets on account id, classify each account as match, mismatch, or missing on one side, handling true zero balances correctly.
Task
A payments company keeps two independent snapshots of account balances: one from its own ledger and one from the partner bank. Each snapshot is a list of records, and a record is a dict with these keys:
"account_id"(str): identifier of the account."month"(str): a month string formatted as"YYYY-MM"."balance_cents"(int): the closing balance in cents. It may be positive, negative, or exactly0.
Write a function reconcile_monthly_balances(internal_records, bank_records, target_month) that compares the two snapshots for the single month target_month. Within one dataset, an account has at most one record for a given month.
The accounts that must be reported are exactly those having at least one record with month == target_month in either dataset. Records whose month differs from target_month (even for an account that also appears in the target month) are ignored.
For each such account, produce a dict with:
"account_id"(str)"internal_balance_cents": the ledger balance, orNoneif the account has no ledger record fortarget_month"bank_balance_cents": the bank balance, orNoneif the account has no bank record fortarget_month"status"(str), chosen by which records are present:"MATCH"— both records present and the balances are equal"MISMATCH"— both records present and the balances differ"MISSING_BANK"— ledger record present, no bank record"MISSING_INTERNAL"— bank record present, no ledger record
Return the list of result dicts ordered by account_id using plain string (lexicographic) comparison. If no account has a record for target_month, return an empty list.
A recorded balance of 0 is a real value, not a missing record. An account with a record whose balance is 0 is treated exactly like one with any other balance.
Constraints
0 <= len(internal_records) <= 1000000 <= len(bank_records) <= 100000- Each
balance_centsvalue is an integer in[-10^12, 10^12] - All
monthvalues (records andtarget_month) are valid"YYYY-MM"strings - Each dataset contains at most one record per
(account_id, month)pair - A balance of
0must never be conflated with a missing record
Examples
Example 1
Input: reconcile_monthly_balances([{'account_id': 'acc_1', 'month': '2024-03', 'balance_cents': 10000}, {'account_id': 'acc_2', 'month': '2024-03', 'balance_cents': 0}, {'account_id': 'acc_3', 'month': '2024-03', 'balance_cents': 5000}, {'account_id': 'acc_1', 'month': '2024-02', 'balance_cents': 9000}], [{'account_id': 'acc_1', 'month': '2024-03', 'balance_cents': 10000}, {'account_id': 'acc_2', 'month': '2024-03', 'balance_cents': 0}, {'account_id': 'acc_4', 'month': '2024-03', 'balance_cents': 0}, {'account_id': 'acc_3', 'month': '2024-02', 'balance_cents': 5000}], '2024-03')
Output: [{'account_id': 'acc_1', 'internal_balance_cents': 10000, 'bank_balance_cents': 10000, 'status': 'MATCH'}, {'account_id': 'acc_2', 'internal_balance_cents': 0, 'bank_balance_cents': 0, 'status': 'MATCH'}, {'account_id': 'acc_3', 'internal_balance_cents': 5000, 'bank_balance_cents': None, 'status': 'MISSING_BANK'}, {'account_id': 'acc_4', 'internal_balance_cents': None, 'bank_balance_cents': 0, 'status': 'MISSING_INTERNAL'}]
Hints
Hint 1
First narrow each dataset down to the target month, then build an account_id to balance lookup for each side.
Hint 2
The set of accounts to report is the union of the account ids in the two lookups; iterate over that union in sorted order.
Hint 3
Determine the status from whether a key exists in each lookup, and use the lookup's get to fill in the balance (which yields None when absent) — never test a balance for truthiness.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a full outer join on account_id, limited to a single month. Do it in three steps:
- Filter and index. Walk each dataset once, keeping only records whose
monthequalstarget_month, and store them in a dict mappingaccount_idtobalance_cents. Records from other months are dropped here, so they can never appear in the output. - Union the keys. The accounts to report form the set of keys from both dicts combined. Sort that set with ordinary string ordering to satisfy the required output order.
- Classify by presence. For each account id, decide the status from dict membership: absent from the ledger dict means
MISSING_INTERNAL; present in the ledger but absent from the bank dict meansMISSING_BANK; present in both meansMATCHif the balances are equal, otherwiseMISMATCH. Fill the balance fields withdict.get, which returnsNonewhen the key is absent.
The critical detail is that classification depends on key membership, not on whether a balance is truthy. A balance of 0 is stored in the dict like any other value, so it is reported as a real balance and compared normally. Testing if balance: would wrongly treat a zero as missing.
Why It Is Correct
- Every account with a record in the target month lands in at least one dict, so it appears in the union; every account without one is filtered out, so no extra rows appear.
- For any key in the union, exactly one status branch applies, because the branches cover "not in ledger", "in ledger not in bank", and "in both" (split into equal/different). This makes the classification exhaustive and mutually exclusive.
MISSING_*rows showNoneon the absent side becausedict.getreturnsNone, while a genuine0is retrieved as0— the two are never confused.- Balances are integer cents, so equality comparison is exact with no floating-point error.
Complexity
Let n and m be the sizes of the two input lists, and k the number of distinct accounts appearing in the target month (k <= n + m).
- Time: O(n + m) to filter and index, plus O(k log k) to sort the union — overall O(n + m + k log k).
- Space: O(k) for the two dicts, the union set, and the output list.
Reference Solution
from typing import List
def reconcile_monthly_balances(internal_records: List[dict], bank_records: List[dict], target_month: str) -> List[dict]:
internal = {
record['account_id']: record['balance_cents']
for record in internal_records
if record['month'] == target_month
}
bank = {
record['account_id']: record['balance_cents']
for record in bank_records
if record['month'] == target_month
}
results = []
for account_id in sorted(set(internal) | set(bank)):
internal_balance = internal.get(account_id)
bank_balance = bank.get(account_id)
if account_id not in internal:
status = 'MISSING_INTERNAL'
elif account_id not in bank:
status = 'MISSING_BANK'
elif internal_balance == bank_balance:
status = 'MATCH'
else:
status = 'MISMATCH'
results.append({
'account_id': account_id,
'internal_balance_cents': internal_balance,
'bank_balance_cents': bank_balance,
'status': status,
})
return results