Layered Invoice Processor with Discounts, Tax, and FX
Arrays & HashingModel answerLast updated
Build a multi-part order cost engine that handles input validation, per-item discounts, order-level tax, multi-currency conversion, and banker's rounding.
Layered Invoice Processor
You are building the backend logic for an invoicing service. Given a product catalog and a list of customer orders, implement a cost calculation engine in three progressive layers. Python is fine; any language works as long as reasoning is clear.
Inputs
price_catalog:dict[str, float]— maps a product code (sku) to its unit price.orders: list of order objects, each containing:order_id: stringitems: list of{ sku: str, qty: int }
Part 1 — Order totals with validation
For every order, compute:
total_cost = sum(qty * unit_price) for each valid item
Validation rules:
- If a
skudoes not appear inprice_catalog, skip that line item and record theskuin a per-ordermissing_skuslist. - A
qtyis valid only if it is a genuine integer (not a float like2.0, not a boolean, notNone), and falls in the range[1, 2^31 − 1]. Anything outside those bounds goes into a per-orderinvalid_itemslist. - Never raise an unhandled exception. Always return both a results list and an
errorsstructure describing what was skipped.
Output: a list of { order_id, total_cost } sorted by order_id ascending. Show the sort key or lambda explicitly.
Part 2 — Discounts and tax
Extend the function signature with two optional inputs:
discounts:dict[str, float]— mapsskuto a discount rate in[0.0, 1.0].- Per-order
tax_ratefield (float in[0.0, 1.0]).
Updated formula:
total_cost = (sum of qty * unit_price * (1 − discount_rate)) * (1 + tax_rate)
- Out-of-range discount or tax values must be reported and ignored (treated as zero), not silently clamped.
- Add a
sort_byparameter that accepts"order_id"or"total_cost", and adescendingflag. Show the sort logic explicitly.
Part 3 — Multi-currency conversion and rounding
Extend orders with an optional currency field (e.g., "EUR", "JPY"). Add:
fx_rates:dict[str, float]— maps each currency code to its value in USD (i.e.,fx_rates["EUR"] = 1.08means 1 EUR = 1.08 USD).target_currency: string (default"USD").
Conversion:
converted_total = total_in_source_currency * fx_rates[source] / fx_rates[target]
- Validate that rates exist and are positive finite numbers. If conversion is impossible for an order, set
total_cost = Noneand record the reason. - Round all monetary outputs to two decimal places using banker's rounding (round half to even). Perform this rounding exactly once, as the final step.
What to address
- Time and space complexity for each part (in terms of number of orders
Nand average items per orderM). - How you would adapt the implementation for very large inputs that do not fit in memory.
- A brief test plan covering: normal cases, unknown SKUs, bad quantities, extreme numeric values, out-of-range rates, sort correctness, and failed currency conversions.
Hints
Hint 1
Floating-point arithmetic is the wrong tool for money. Wrap every price, rate, and quantity in Decimal as early as possible, read floats via Decimal(str(x)) to avoid binary representation errors, and call .quantize() exactly once at the very end.
Hint 2
Validate at the boundary, not mid-computation. Parse the catalog and discount map once before the order loop. Then validate each order and each line item as you encounter them. Separation keeps the happy path clean and the error accumulation consistent.
Hint 3
For sorting when total_cost can be None, decide on a policy (e.g., failed orders always sort last) and enforce it explicitly rather than relying on comparison behavior that varies by language. For the total_cost sort, apply a secondary sort by order_id first to get a stable, deterministic tie-break.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a data-processing problem, not an algorithmic one. Interviewers are testing three things: numeric precision discipline, defensive input handling, and clean layered design.
Core principles before writing any code
Money is not a float. IEEE 754 floats cannot represent most decimal fractions exactly. 0.1 + 0.2 != 0.3 in floating point. Use Decimal throughout. Read incoming floats with Decimal(str(x)) — this gives Decimal("0.1") rather than the binary approximation Decimal("0.1000000000000000055511..."). Round once, at the very end, with ROUND_HALF_EVEN (banker's rounding), which is the standard for financial systems because it eliminates the upward bias of always rounding 0.5 up.
Validate at the boundary. Check the catalog and discount map once before the main loop. Inside the loop, validate each order and each line item as you reach it. Never let bad data propagate into arithmetic — skip it, record it, and move on.
Build in layers. Part 1 is the core loop. Part 2 adds two multipliers and a configurable sort. Part 3 adds one conversion step. A single function with optional parameters handles all three without duplication.
Validation rules worth stating explicitly
qtymust be a genuine Pythonintand must not be abool(in Python,boolis a subclass ofint, soisinstance(True, int)isTrue— you must check forboolfirst). Valid range:1 ≤ qty ≤ 2^31 − 1. Python integers don't overflow natively, so the upper cap is enforced explicitly to mirror typed-language behavior.- Prices must be finite and non-negative.
- Discount and tax rates must be finite and in
[0, 1]. Out-of-range means invalid and reported — not silently clamped to the boundary. - FX rates must be finite and strictly positive.
Full implementation
from decimal import Decimal, ROUND_HALF_EVEN, InvalidOperation, localcontext
MAX_QTY = 2**31 - 1
CENT = Decimal("0.01")
def _to_decimal(x):
"""Convert a numeric value to Decimal, or return None if invalid."""
if isinstance(x, bool) or not isinstance(x, (int, float, Decimal)):
return None
try:
d = Decimal(str(x))
except (InvalidOperation, ValueError):
return None
return d if d.is_finite() else None
def _valid_rate(x):
"""Return a Decimal in [0, 1], or None if out of range or non-numeric."""
d = _to_decimal(x)
return d if d is not None and Decimal(0) <= d <= Decimal(1) else None
def _valid_qty(q):
return isinstance(q, int) and not isinstance(q, bool) and 1 <= q <= MAX_QTY
def calculate_costs(
price_catalog,
orders,
discounts=None,
fx_rates=None,
target_currency="USD",
sort_by="order_id",
descending=False,
):
errors = {"global": [], "orders": {}}
# Normalize fx_rates; always ensure USD baseline
fx = fx_rates if isinstance(fx_rates, dict) else {}
if "USD" not in fx:
fx = {**fx, "USD": 1}
if sort_by not in ("order_id", "total_cost"):
errors["global"].append(f"unknown sort_by {sort_by!r}; defaulting to order_id")
sort_by = "order_id"
# Validate catalog once up front
catalog = {}
for sku, price in (price_catalog if isinstance(price_catalog, dict) else {}).items():
d = _to_decimal(price)
if d is None or d < 0:
errors["global"].append(f"invalid price for sku {sku!r}: {price!r}")
else:
catalog[sku] = d
# Validate discounts once up front
valid_discounts = {}
for sku, rate in (discounts if isinstance(discounts, dict) else {}).items():
d = _valid_rate(rate)
if d is None:
errors["global"].append(f"invalid discount for sku {sku!r}: {rate!r}")
else:
valid_discounts[sku] = d
def get_fx_rate(currency):
"""Return a positive Decimal rate, or None if missing/invalid."""
if not isinstance(currency, str):
return None
r = _to_decimal(fx.get(currency))
return r if r is not None and r > 0 else None
target_rate = get_fx_rate(target_currency)
if target_rate is None:
errors["global"].append(
f"missing or invalid FX rate for target currency {target_currency!r}"
)
results = []
for idx, order in enumerate(orders if isinstance(orders, list) else []):
if not isinstance(order, dict) or not isinstance(order.get("order_id"), str):
errors["global"].append(f"malformed order at index {idx}; skipped")
continue
oid = order["order_id"]
rep = {"missing_skus": [], "invalid_items": [], "other": []}
items = order.get("items")
if not isinstance(items, list):
rep["other"].append("'items' is not a list")
items = []
total_cost = None
with localcontext() as ctx:
ctx.prec = 60 # high precision; round only at the end
subtotal = Decimal(0)
for item in items:
if not isinstance(item, dict) or not isinstance(item.get("sku"), str):
rep["invalid_items"].append(item)
continue
sku = item["sku"]
qty = item.get("qty")
if sku not in catalog:
rep["missing_skus"].append(sku)
continue
if not _valid_qty(qty):
rep["invalid_items"].append(item)
continue
discount = valid_discounts.get(sku, Decimal(0))
subtotal += qty * catalog[sku] * (1 - discount)
# Apply tax
tax = Decimal(0)
raw_tax = order.get("tax_rate")
if raw_tax is not None:
t = _valid_rate(raw_tax)
if t is None:
rep["other"].append(f"invalid tax_rate {raw_tax!r}; treated as 0")
else:
tax = t
# Currency conversion
src_currency = order.get("currency", "USD")
src_rate = get_fx_rate(src_currency)
if src_rate is None or target_rate is None:
rep["other"].append(
f"cannot convert {src_currency!r} -> {target_currency!r}"
)
else:
try:
raw_total = subtotal * (1 + tax) * src_rate / target_rate
# Single rounding step, banker's rounding
total_cost = raw_total.quantize(CENT, rounding=ROUND_HALF_EVEN)
except InvalidOperation:
rep["other"].append("numeric overflow while computing total")
results.append({"order_id": oid, "total_cost": total_cost, "currency": target_currency})
if any(rep.values()):
errors["orders"][oid] = {k: v for k, v in rep.items() if v}
# Sorting
if sort_by == "order_id":
results.sort(key=lambda r: r["order_id"], reverse=descending)
else:
# Orders with None total sort last regardless of direction
ok = [r for r in results if r["total_cost"] is not None]
failed = [r for r in results if r["total_cost"] is None]
ok.sort(key=lambda r: r["order_id"]) # stable tie-break first
ok.sort(key=lambda r: r["total_cost"], reverse=descending)
failed.sort(key=lambda r: r["order_id"])
results = ok + failed
return {"results": results, "errors": errors}
Complexity
| Part | Time | Space |
|---|---|---|
| 1 | O(N × M) | O(N) results + O(SKUs) catalog |
| 2 | Same, with constant extra multiplications | Same |
| 3 | Same, plus O(currencies) for FX lookup | Same |
N = number of orders, M = average items per order. All catalog, discount, and FX lookups are O(1) dict accesses.
Scaling to large inputs
For inputs that don't fit in memory, process orders as a stream (generator or file reader) rather than loading the full list. Write results incrementally to a file or message queue. The catalog and discount maps must still fit in memory — if those are also large, shard by SKU prefix or serve them from a key-value store with local caching.
Test plan
- Normal case: valid SKUs, valid quantities, correct totals.
- Missing SKU: item with unknown SKU skipped, recorded in
missing_skus, rest of order still totals correctly. - Invalid qty:
0,-1,2.0,True,None,2**31— all rejected and recorded. - Extreme values: very large valid qty, price near zero, subtotal near
Decimaloverflow. - Discount/tax edge cases: rate exactly
0.0, rate exactly1.0, rate1.01(rejected),None(skipped gracefully). - Sort correctness: verify ascending/descending by both keys; verify
Nonetotals always land last. - Currency conversion failures: missing source rate, missing target rate, rate of zero.
- Malformed orders: non-dict, missing
order_id,itemsis not a list — none should raise.
Common mistakes
- Using
floatfor any monetary value — introduces rounding drift that accumulates across items. - Rounding after each line item instead of once at the end — amplifies error.
- Forgetting that
isinstance(True, int)isTruein Python —boolmust be excluded explicitly from qty validation. - Silently clamping out-of-range rates instead of reporting them — callers can't audit what was applied.
- Sorting
Nonetotals alongside numbers without a guard — raisesTypeErrorin Python 3.