Reconcile Payments with Invoices Using Memo and Amount
StringsAuto-graded · 18 test casesLast updated
Tests multi-pattern substring search, hash-based indexing, and greedy reconciliation with priority-based tie-breaking across two matching strategies.
You are building a payment reconciliation system. Given two collections—a list of outstanding invoices and a list of incoming payments—your job is to pair each payment with at most one invoice using a two-phase matching strategy.
Each invoice contains:
id: a unique string identifieramount: a numeric valuedate: an ISO date string (YYYY-MM-DD)
Each payment contains:
amount: a numeric valuememo: a text field that may reference invoice identifiersdate: an ISO date string
Matching Rules
Process payments in the order given. For each payment, attempt to match it with an unmatched invoice using the following precedence:
Phase 1: Identifier Match
Search the payment's memo field for any invoice id as a substring. If one or more invoice identifiers appear and those invoices are still unmatched:
- Select the invoice with the largest amount.
- If multiple invoices share that largest amount, choose the one with the earliest date.
- If still tied, choose the one with the lexicographically smallest
id.
Phase 2: Exact Amount Match
If no unmatched invoice identifier was found in the memo, look for an unmatched invoice whose amount exactly equals the payment amount:
- If multiple invoices have that amount, choose the one with the earliest date.
- If still tied, choose the one with the lexicographically smallest
id.
Output
Return a list of matched pairs [payment_index, invoice_id] in the order payments were processed. Payments that match no invoice are omitted from the result.
Once an invoice is matched, it becomes unavailable for subsequent payments.
Constraints
- 1 ≤ number of invoices ≤ 10,000
- 1 ≤ number of payments ≤ 10,000
- Invoice
idstrings are unique and non-empty - Amounts are non-negative floats
- Date strings follow ISO format; missing dates default to empty string
- Memo strings may be empty or missing
Examples
Example 1
Input: reconcile_payments([{'id': 'INV-001', 'amount': 100, 'date': '2023-01-01'}, {'id': 'INV-002', 'amount': 200, 'date': '2023-01-02'}], [{'amount': 100, 'memo': 'Paid INV-001'}, {'amount': 200, 'memo': 'Final balance'}])
Output: [[0, 'INV-001'], [1, 'INV-002']]
Example 2
Input: reconcile_payments([{'id': 'A', 'amount': 50, 'date': '2024-02-01'}, {'id': 'B', 'amount': 100, 'date': '2024-01-01'}], [{'amount': 999, 'memo': 'A and B'}])
Output: [[0, 'B']]
Example 3
Input: reconcile_payments([{'id': 'X1', 'amount': 25, 'date': '2024-03-01'}, {'id': 'X2', 'amount': 25, 'date': '2024-01-01'}], [{'amount': 25, 'memo': 'no reference'}, {'amount': 25, 'memo': 'still no reference'}])
Output: [[0, 'X2'], [1, 'X1']]
Hints
Hint 1
For efficient substring matching of many patterns in each memo, consider using an Aho-Corasick automaton instead of checking each invoice ID individually.
Hint 2
Track which invoices have already been matched using a boolean array to ensure each invoice is used at most once.
Hint 3
A single comparison key of (-amount, date, id) handles tie-breaking for both phases: phase 1 selects the highest amount first, and phase 2 automatically uses date and id when amounts are equal.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This reconciliation problem requires processing payments sequentially and greedily matching each to an available invoice using a two-tier strategy.
Phase 1: Identifier Substring Matching
The core challenge is efficiently finding which invoice identifiers appear in each payment memo. A naive approach checking every invoice ID against every memo character would require O(P · I · L) operations—too slow for 10,000 payments and invoices.
Instead, we use an Aho-Corasick automaton, which is designed for multi-pattern substring search:
- Build a trie containing all invoice IDs
- Add failure links using breadth-first search (similar to KMP for tries)
- Propagate terminal markers along failure links so all matching patterns are reported
- Scan each memo in linear time, collecting all invoice IDs that appear as substrings
Among the matching unmatched invoices, we select based on priority: highest amount first, then earliest date, then lexicographically smallest ID.
Phase 2: Exact Amount Fallback
If no unmatched invoice ID was found in the memo, we scan all invoices for an exact amount match. The same priority rules apply, but since all candidates share the same amount, selection reduces to earliest date then smallest ID.
Correctness
- The two-phase structure enforces the precedence rule: amount matching only occurs when ID matching yields no unmatched candidates
- A boolean array tracks which invoices have been matched, ensuring each is used at most once
- The priority comparison key
(-amount, date, id)provides a strict total ordering that handles both phases correctly - Aho-Corasick guarantees all substring occurrences are found, including overlapping patterns
Complexity
Let S_I = total length of invoice IDs, S_M = total memo length, Z = total ID occurrences found.
- Time: O(S_I) to build the automaton, O(S_M + Z) to scan all memos, O(P · I) worst-case for amount fallback per payment (can be optimized to O(I log I) preprocessing + amortized O(1) per payment using pre-grouped buckets)
- Space: O(S_I + I) for the automaton and tracking arrays
The algorithm handles all edge cases: already-matched invoices are skipped, multiple IDs in one memo are all considered, and payments with no match are omitted from output.
from collections import deque
from typing import List, Dict
def reconcile_payments(invoices: List[Dict], payments: List[Dict]) -> List[List]:
# Build Aho-Corasick automaton for efficient multi-pattern substring matching
next_nodes = [{}]
fail = [0]
terminal = [[]]
for idx, invoice in enumerate(invoices):
node = 0
for char in invoice['id']:
if char not in next_nodes[node]:
next_nodes[node][char] = len(next_nodes)
next_nodes.append({})
fail.append(0)
terminal.append([])
node = next_nodes[node][char]
terminal[node].append(idx)
# Build failure links using BFS
queue = deque()
for child in next_nodes[0].values():
queue.append(child)
while queue:
node = queue.popleft()
for char, child in next_nodes[node].items():
queue.append(child)
fallback = fail[node]
while fallback and char not in next_nodes[fallback]:
fallback = fail[fallback]
fail[child] = next_nodes[fallback].get(char, 0)
terminal[child].extend(terminal[fail[child]])
matched = [False] * len(invoices)
result = []
def priority_key(invoice_idx):
inv = invoices[invoice_idx]
return (-inv['amount'], inv.get('date', ''), inv['id'])
for pay_idx, payment in enumerate(payments):
# Phase 1: Search memo for invoice IDs
node = 0
candidates = []
for char in payment.get('memo', ''):
while node and char not in next_nodes[node]:
node = fail[node]
node = next_nodes[node].get(char, 0)
for inv_idx in terminal[node]:
if not matched[inv_idx]:
candidates.append(inv_idx)
best = None
for inv_idx in candidates:
if best is None or priority_key(inv_idx) < priority_key(best):
best = inv_idx
# Phase 2: Exact amount match if no ID match found
if best is None:
for inv_idx, invoice in enumerate(invoices):
if not matched[inv_idx] and invoice['amount'] == payment['amount']:
if best is None or priority_key(inv_idx) < priority_key(best):
best = inv_idx
if best is not None:
matched[best] = True
result.append([pay_idx, invoices[best]['id']])
return result