Reconcile Payments Against Open Invoices in Three Tiers
Arrays & HashingAuto-graded · 21 test casesLast updated
Process payments in order, pairing each with an invoice by ID plus amount, then by unique amount, then by closest amount within a percentage tolerance.
Reconcile Payments Against Open Invoices
A billing system receives a list of payments and a list of open invoices. Each record is a dictionary with an id (string) and an amount (non-negative number). Pair payments with invoices so that each invoice is used by at most one payment.
Write a function reconcile_payments(payments, invoices) that returns the pairs it finds.
Processing order
Handle the payments one at a time, in the order given. An invoice that has already been paired is no longer available to later payments. For each payment, try the following tiers in order and stop at the first one that selects an invoice.
Two amounts are treated as equal when they differ by at most 1e-9. Let eps = 1e-9.
-
ID and amount match. Look at the available invoices whose
idis identical to the payment'sidand whose amount equals the payment's amount. If there are several, take the one that appears earliest ininvoices. -
Unique amount match. Count the available invoices whose amount equals the payment's amount. If exactly one exists, pair the payment with it. If there are zero or several, move on to tier 3.
-
Tolerance match. Consider every available invoice
invthat satisfies|payment_amount - inv_amount| <= 0.03 * inv_amount + epsThe tolerance is 3 percent of the invoice amount. Among these candidates, choose the one with the smallest
|payment_amount - inv_amount|. If distances tie, choose the invoice with the lexicographically smallerid(string comparison). If that also ties, choose the one that appears earliest ininvoices.
If no tier selects an invoice, the payment stays unmatched and is left out of the result.
Tier 3 also covers payments whose amount is shared by several available invoices. Those invoices are at distance 0, so the tie-break rules decide among them.
Output
Return a list of [payment_id, invoice_id] pairs (two-element lists of strings), one per matched payment, in the same order as the payments appear in the input.
Constraints
0 <= len(payments), len(invoices) <= 10,000- Every
idis a string. Invoice ids may repeat. - Amounts are non-negative numbers (integers or floats).
- Use
eps = 1e-9for every amount-equality check, and 3% for the tolerance. - Unmatched payments do not appear in the result. Empty inputs give an empty list.
Examples
Example 1
Input: reconcile_payments([{'id': 'p1', 'amount': 100}, {'id': 'p2', 'amount': 205}], [{'id': 'i1', 'amount': 100}, {'id': 'i2', 'amount': 200}])
Output: [['p1', 'i1'], ['p2', 'i2']]
Hints
Hint 1
Keep a set of invoice positions that are still available, and remove a position as soon as a payment claims it.
Hint 2
Each payment runs through the three tiers independently and in order. In tier 2, count only available invoices whose amount equals the payment amount, and match only if the count is exactly 1.
Hint 3
In tier 3, build tuples of (distance, invoice id, position) for every available invoice that is within tolerance and take the minimum. The tuple ordering gives you the required tie-breaks.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulate the process exactly as described. Keep a set of invoice positions that are still available. For each payment, in input order, try three tiers and stop at the first one that picks an invoice.
- ID and amount. Pre-build a dictionary from invoice id to the list of positions with that id, in input order. For a payment, walk the positions for its id and take the first one that is available and whose amount is within
1e-9of the payment's amount. - Unique amount. Pre-build a dictionary from the invoice amount (rounded to 9 decimals) to the list of positions with that amount. Filter that list down to available invoices whose amount is really within
1e-9of the payment's. If exactly one remains, take it. Zero or several candidates mean this tier does not decide. - Tolerance. Scan all available invoices. Keep those with
|p - inv| <= 0.03 * inv + 1e-9. Build tuples(distance, invoice_id, position)and take the minimum. Tuple comparison applies the tie-breaks in the required order: smaller distance, then smaller id, then earlier position.
When an invoice is chosen, remove it from the available set and record [payment_id, invoice_id]. Since payments are processed in order, the output is already in payment order.
Why it is correct
Each payment is decided by the first applicable tier, which is the stated priority. Removing a claimed invoice from the available set means it cannot be reused. It also means the "exactly one" check in tier 2 only sees invoices that are still unmatched. Tier 3 includes invoices at distance 0, so a payment whose amount is shared by several invoices falls through to it and is resolved by the tie-break rules. Using min over (distance, id, position) tuples encodes those rules directly.
Complexity
Let P be the number of payments and N the number of invoices.
- Building the indexes takes O(N).
- Tiers 1 and 2 are O(1) per payment on average.
- Tier 3 scans the available invoices, so it costs O(N) per payment that reaches it.
- Total time is O(N + P·N) in the worst case, about 10^8 simple operations at the maximum size. Typical inputs resolve most payments in tiers 1 and 2.
- Space is O(N + P).
Reference solution
from typing import List, Dict
from collections import defaultdict
def reconcile_payments(payments: List[Dict], invoices: List[Dict]) -> List[List[str]]:
tolerance = 0.03
epsilon = 1e-9
available = set(range(len(invoices)))
by_id = defaultdict(list)
by_amount = defaultdict(list)
for j, invoice in enumerate(invoices):
by_id[invoice['id']].append(j)
by_amount[round(float(invoice['amount']), 9)].append(j)
matches = []
for payment in payments:
pid = payment['id']
amount = float(payment['amount'])
chosen = None
# Tier 1: same id and equal amount.
for j in by_id.get(pid, []):
if j in available and abs(float(invoices[j]['amount']) - amount) <= epsilon:
chosen = j
break
# Tier 2: exactly one available invoice with an equal amount.
if chosen is None:
exact_candidates = [
j for j in by_amount.get(round(amount, 9), [])
if j in available and abs(float(invoices[j]['amount']) - amount) <= epsilon
]
if len(exact_candidates) == 1:
chosen = exact_candidates[0]
# Tier 3: closest available invoice within 3% of the invoice amount.
if chosen is None:
candidates = []
for j in available:
invoice_amount = float(invoices[j]['amount'])
difference = abs(amount - invoice_amount)
limit = tolerance * invoice_amount
if difference <= limit + epsilon:
candidates.append((difference, str(invoices[j]['id']), j))
if candidates:
chosen = min(candidates)[2]
if chosen is not None:
available.remove(chosen)
matches.append([str(pid), str(invoices[chosen]['id'])])
return matches