Billing Reconciliation: Match Payments to Invoices in Three Stages
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests incremental lookup design by matching payments to invoices via explicit ID, then earliest-dated exact-amount fallback, then a forgiveness range, with closed-invoice tracking throughout.
Billing Reconciliation: Match Payments to Invoices in Three Stages
You are building the reconciliation engine for an accounts-receivable system. Given a collection of invoices and a batch of payments, your task is to determine which invoice each payment settles — or report that no match was found.
Data Formats
All inputs are Python dicts. Fields and types are fixed.
An invoice dict has:
"id"— a unique string identifier"amount"— a non-negative integer (minor currency units, e.g. cents)"date"— an ISO-8601 date string ("YYYY-MM-DD")
A payment dict has:
"id"— a string identifier for this payment"amount"— a non-negative integer"invoice_id"(optional) — the string ID of the invoice this payment intends to settle
Matching Rules
Payments are processed in order, one at a time, and each decision is final. An invoice that has been matched is closed and cannot be matched again.
Apply the following rules in priority order for each payment:
Rule 1 — Explicit invoice ID.
If the payment includes an "invoice_id" key, look up that invoice by ID and match it, regardless of whether the payment amount equals the invoice amount. If no invoice with that ID exists, or the invoice is already closed, report no match for this payment. Do not fall back to Rule 2 in either failure case.
Rule 2 — Amount fallback with forgiveness.
If the payment has no "invoice_id", find every open invoice whose amount is within the closed interval [payment_amount − f, payment_amount + f], where f is the non-negative integer forgiveness parameter. Among all such candidates, match the one with the earliest date. If two candidates share the earliest date, break the tie by choosing the one whose invoice ID comes first in lexicographic order.
Setting f = 0 makes Rule 2 require an exact amount match.
Return Value
Return a list of results, one per payment, in the same order. Each result is either:
- the string ID of the matched invoice, or
Noneif no match was found.
Constraints
0 ≤ len(invoices) ≤ 10^40 ≤ len(payments) ≤ 10^4- Invoice IDs are unique strings.
0 ≤ amount ≤ 10^9for both invoices and payments.0 ≤ forgiveness ≤ 10^9datestrings are valid ISO-8601 dates and compare correctly as plain strings.- A payment with
"invoice_id"present but set to an ID that does not exist in the invoice list yieldsNone— no fallback. - If no invoices are given, every payment yields
None.
Examples
Example 1
Input: reconcile_payments([{'id': 'inv-1', 'amount': 1000, 'date': '2024-01-02'}, {'id': 'inv-2', 'amount': 1000, 'date': '2024-01-01'}, {'id': 'inv-3', 'amount': 1200, 'date': '2024-01-03'}], [{'id': 'p1', 'amount': 999, 'invoice_id': 'inv-1'}, {'id': 'p2', 'amount': 1000}, {'id': 'p3', 'amount': 1100}, {'id': 'p4', 'amount': 1200, 'invoice_id': 'missing'}], 100)
Output: ['inv-1', 'inv-2', 'inv-3', None]
Example 2
Input: reconcile_payments([{'id': 'a', 'amount': 500, 'date': '2024-02-01'}, {'id': 'b', 'amount': 500, 'date': '2024-01-01'}], [{'id': 'p1', 'amount': 500}, {'id': 'p2', 'amount': 500}, {'id': 'p3', 'amount': 500}], 0)
Output: ['b', 'a', None]
Example 3
Input: reconcile_payments([{'id': 'x', 'amount': 700, 'date': '2024-01-01'}], [{'id': 'p1', 'amount': 699, 'invoice_id': 'x'}, {'id': 'p2', 'amount': 700}], 10)
Output: ['x', None]
Hints
Hint 1
For Rule 1, build a dict mapping invoice ID → invoice index before processing any payments so each lookup is O(1).
Hint 2
For Rule 2, sort the unique invoice amounts and store a min-heap per amount bucket (keyed by (date, invoice_id, index)). Binary search gives you the bucket range that falls inside the forgiveness window, then you need the earliest still-open entry across that range.
Hint 3
To query the minimum across a contiguous range of buckets efficiently, layer a segment tree on top of the per-amount heaps. Each segment-tree node caches the current minimum of its subtree, and you update it whenever a matched invoice is removed from a heap.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has three nested concerns that map cleanly to three separate data structures built during a single pre-processing pass.
Rule 1 — O(1) ID lookup
Build a plain dict mapping every invoice's string ID to its position in the invoice list. Looking up a payment's explicit invoice_id is then a single dict access. If the key is missing or the invoice is already closed, return None immediately with no fallback — that constraint is explicit in the problem.
Rule 2 — Earliest open invoice in an amount range
For an exact-match query (forgiveness = 0) a dict keyed by amount suffices, but the forgiveness window requires range queries. The approach is:
- Collect the sorted list of distinct amounts that appear in the invoice list. Call this array
distinct_amounts. - Maintain one min-heap per amount bucket. Each entry in a heap is the tuple
(date, invoice_id, original_index). Lexicographic comparison on this tuple gives "earliest date, then lex-smallest id" for free. - When a payment has no explicit ID, binary-search
distinct_amountsfor the left and right boundary of[payment_amount − f, payment_amount + f]. The answer is the minimum tuple across all heaps in that index range.
Efficient range minimum — segment tree
Scanning every heap in the range costs O(k) per payment in the worst case, where k is the number of distinct amounts in the window. Instead, lay a segment tree on top of the heap array. Each leaf stores the current minimum entry (top of its heap, after lazily discarding closed invoices). Each internal node caches the minimum of its two children.
range_min(lo, hi)walks the segment tree in O(log A) time, where A is the number of distinct amounts.- After closing an invoice, call
refresh(bucket)to pop stale entries from that heap and propagate the new minimum up the tree in O(log A).
Why this is correct
- The segment tree always reflects the current minimum of each live heap because
refreshis called every time an invoice is closed. - Lazy deletion inside
refresh(popping closed entries before reading the heap top) ensures closed invoices are never returned as candidates. - Setting
f = 0makes the binary search return a range of at most one bucket (the exact-match bucket), reproducing Part 2 behavior exactly. - The ID path never touches the segment tree, so the two rules are fully independent.
Complexity
Let n = number of invoices, m = number of payments, A = number of distinct invoice amounts (A ≤ n).
| Phase | Time | Space |
|---|---|---|
| Pre-processing (heaps + tree) | O(n log n) | O(n) |
| Per payment — Rule 1 | O(1) amortized | — |
| Per payment — Rule 2 range query | O(log A) | — |
refresh after a match | O(log n + log A) | — |
| Total | O((n + m) log n) | O(n) |
Reference Solution
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush
from typing import Dict, List, Optional
def reconcile_payments(
invoices: List[Dict],
payments: List[Dict],
forgiveness: int,
) -> List[Optional[str]]:
if not invoices:
return [None] * len(payments)
active = [True] * len(invoices)
# Rule 1: direct ID → index map
by_id: Dict[str, int] = {}
for i, inv in enumerate(invoices):
by_id[inv["id"]] = i
# Rule 2: one min-heap per distinct amount bucket
distinct_amounts = sorted({inv["amount"] for inv in invoices})
amount_to_bucket = {amt: pos for pos, amt in enumerate(distinct_amounts)}
heaps: List[List] = [[] for _ in distinct_amounts]
for i, inv in enumerate(invoices):
bucket = amount_to_bucket[inv["amount"]]
heappush(heaps[bucket], (inv["date"], inv["id"], i))
# Segment tree over bucket array (1-indexed, power-of-two size)
size = 1
while size < len(distinct_amounts):
size <<= 1
tree: List[Optional[tuple]] = [None] * (2 * size)
def _peek(bucket: int) -> Optional[tuple]:
h = heaps[bucket]
while h and not active[h[0][2]]:
heappop(h)
return h[0] if h else None
def refresh(bucket: int) -> None:
node = size + bucket
tree[node] = _peek(bucket)
node >>= 1
while node:
left = tree[2 * node]
right = tree[2 * node + 1]
if left is None:
tree[node] = right
elif right is None:
tree[node] = left
else:
tree[node] = min(left, right)
node >>= 1
for b in range(len(distinct_amounts)):
refresh(b)
def range_min(lo: int, hi: int) -> Optional[tuple]:
lo += size
hi += size
best: Optional[tuple] = None
while lo < hi:
if lo & 1:
v = tree[lo]
if v is not None and (best is None or v < best):
best = v
lo += 1
if hi & 1:
hi -= 1
v = tree[hi]
if v is not None and (best is None or v < best):
best = v
lo >>= 1
hi >>= 1
return best
results: List[Optional[str]] = []
for payment in payments:
explicit_id = payment.get("invoice_id")
chosen: Optional[int] = None
if explicit_id is not None:
idx = by_id.get(explicit_id)
if idx is not None and active[idx]:
chosen = idx
else:
lo = bisect_left(distinct_amounts, payment["amount"] - forgiveness)
hi = bisect_right(distinct_amounts, payment["amount"] + forgiveness)
best_key = range_min(lo, hi)
if best_key is not None:
chosen = best_key[2]
if chosen is None:
results.append(None)
else:
active[chosen] = False
results.append(invoices[chosen]["id"])
refresh(amount_to_bucket[invoices[chosen]["amount"]])
return results