Policy-Driven Spending Report Checker
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests whether a candidate can implement a multi-scope rule evaluation pipeline that collects all violations across item-level, aggregate, and relational policy checks.
Problem Statement
Financial compliance teams need automated tools that can scan submitted spending reports and flag every policy breach — not just the first one found. Your task is to build a rule-based spending report checker that applies a configurable set of policies to a list of expense entries and returns all detected violations.
Data Format
Each expense entry is a dictionary with these keys:
| Key | Type | Description |
|---|---|---|
id | str | Unique identifier for the entry |
category | str | Spending category, e.g. "MEALS", "AIRFARE" |
amount | float | Positive amount with up to 2 decimal places |
expense_date | str | ISO date string, e.g. "2025-03-01" |
has_receipt | bool | Whether a receipt was attached |
Each policy rule is a dictionary with a "type" key and type-specific parameters (see below). An optional "rule_name" key overrides the default name used in violation output.
Rule Types
Your checker must support exactly three rule types:
receipt_required
Parameters: categories (list of strings), threshold (float).
Any entry whose category is in categories and whose amount is strictly greater than threshold must have has_receipt == True. Each offending entry produces its own violation.
Default rule_name: "ReceiptRequiredRule"
daily_category_cap
Parameters: category (string), daily_limit (float).
The combined total of all entries matching category on a single date must not be strictly greater than daily_limit. When a date's total exceeds the cap, produce one violation listing every entry from that date (in input order). Process dates in ascending sorted order.
Default rule_name: "DailyCategoryCapRule"
mutual_exclusion
Parameters: category_a (string), category_b (string).
Entries of category_a and entries of category_b must not share the same expense_date. Each conflicting date produces one violation whose item_ids lists all category_a entries for that date (in input order) followed by all category_b entries for that date (in input order). Process conflict dates in ascending sorted order.
Default rule_name: "MutualExclusionRule"
An unknown type value must raise a ValueError.
Output Format
Return a flat list of violation dictionaries, one per detected breach, in rule-declaration order. Within a single rule, violations appear in the order described above for that rule type. Each violation dictionary has exactly these keys:
{
"rule_name": str, # default or overridden name
"message": str, # human-readable description
"item_ids": list # IDs of the offending entries; empty list if report-wide
}
The message field for each rule must follow this exact format:
receipt_required:"{category} expense exceeds {threshold} and requires a receipt"daily_category_cap:"{category} expenses on {date} total {total:g}, exceeding daily limit {limit:g}"mutual_exclusion:"{category_a} and {category_b} expenses cannot both appear on {date}"
Design Note
The checking logic for each rule type is completely self-contained. Processing one rule must never affect another, and a breach found by one rule must not prevent subsequent rules from running. Every applicable violation across all rules must appear in the output.
Constraints
- The report may contain up to 10^4 expense entries.
- All
amountvalues are positive floats with up to 2 decimal places. - Threshold and cap comparisons are strictly greater than (
>); values exactly equal to the threshold or cap are not violations. - Dates are ISO-format strings that sort lexicographically in calendar order.
- The input entry list is not modified by your function.
Examples
Example 1
Input: check_spending_report([{'id': 'e1', 'category': 'MEALS', 'amount': 80, 'expense_date': '2025-03-01', 'has_receipt': False}, {'id': 'e2', 'category': 'MEALS', 'amount': 50, 'expense_date': '2025-03-01', 'has_receipt': True}, {'id': 'e3', 'category': 'CAR_RENTAL', 'amount': 120, 'expense_date': '2025-03-01', 'has_receipt': True}, {'id': 'e4', 'category': 'MILEAGE', 'amount': 45, 'expense_date': '2025-03-01', 'has_receipt': True}], [{'type': 'receipt_required', 'threshold': 75, 'categories': ['MEALS']}, {'type': 'daily_category_cap', 'category': 'MEALS', 'daily_limit': 100}, {'type': 'mutual_exclusion', 'category_a': 'CAR_RENTAL', 'category_b': 'MILEAGE'}])
Output: [{'rule_name': 'ReceiptRequiredRule', 'message': 'MEALS expense exceeds 75 and requires a receipt', 'item_ids': ['e1']}, {'rule_name': 'DailyCategoryCapRule', 'message': 'MEALS expenses on 2025-03-01 total 130, exceeding daily limit 100', 'item_ids': ['e1', 'e2']}, {'rule_name': 'MutualExclusionRule', 'message': 'CAR_RENTAL and MILEAGE expenses cannot both appear on 2025-03-01', 'item_ids': ['e3', 'e4']}]
Hints
Hint 1
For each rule type, think about what grouping structure makes the check efficient — receipt rules need no grouping, cap rules need entries bucketed by date, and exclusion rules need two separate date-to-entries maps that you then intersect.
Hint 2
All three rule types share the same outer contract: iterate over rules, dispatch on type, collect results. A dictionary mapping type strings to handler functions keeps the dispatch clean and makes it easy to add new rule types later without touching the main loop.
Hint 3
Watch the ordering requirements carefully: daily cap and mutual exclusion violations must be emitted in ascending date order (sort the date keys before iterating), and within a mutual exclusion violation the category_a items come before category_b items.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that every rule type, regardless of its scope, shares the same outer contract: given the full list of entries, produce zero or more violation dicts. This means the engine itself can be a simple loop over policies — dispatch on type, collect results, repeat. No rule can interrupt another.
Dispatching without a long if/elif chain
A lookup table (DEFAULT_NAMES) keyed by type string serves two purposes: it maps each known type to its default rule name, and its key set is the cheapest possible validity check — any type not in the table immediately raises ValueError. This is the pattern that makes the design open to extension: adding a new rule type means adding an entry to the table and writing a new branch (or, in a more decoupled design, registering a handler function), never editing existing logic.
Receipt Required (item-level)
One linear scan through entries. For each entry, three conditions must all hold: category is in the allowed set, amount is strictly greater than the threshold, and has_receipt is False. Each offending entry produces its own violation immediately, so output order follows input order naturally.
Daily Category Cap (aggregate)
Group matching entries into a defaultdict(list) keyed by expense_date. After the single pass, iterate over dates in sorted order (lexicographic sort of ISO strings equals calendar order). For each date, sum the bucket. If the sum is strictly greater than daily_limit, emit one violation whose item_ids lists every entry in the bucket — because the excess is collective, not attributable to any single item.
Mutual Exclusion (relational)
Build two defaultdict(list) maps independently, one per category. Then compute the set intersection of their key sets — those are exactly the conflict dates. Iterate conflict dates in sorted order; for each, concatenate the category-A entry IDs with the category-B entry IDs (each sub-list in input order) to form item_ids.
Why it is correct
- Strict inequality (
>) is used for both threshold and cap comparisons, so boundary values never trigger a violation. - Each rule processes the full entry list independently, so no rule's output can mask or prevent another's.
- Sorted date iteration guarantees stable, deterministic output regardless of insertion order.
- The
{total:g}format specifier drops unnecessary trailing zeros (e.g.,130not130.0), matching the expected message strings exactly.
Complexity
Let n = number of entries, R = number of rules, d = number of distinct dates.
- Time: each rule is one
O(n)pass plus at most anO(d log d)sort. Total:O(R · (n + d log d)). Withn = 10^4this is fast in practice. - Space:
O(n)per grouping rule for the date buckets, plusO(v)for the output wherevis the number of violations.
Edge Cases
- Empty entry list → returns
[](loops over groups find nothing). - Amount or total exactly equal to threshold or cap → not a violation (strict
>). - Multiple dates over a daily cap → one violation per date, in sorted order.
- One category absent on a date where the other appears → no mutual exclusion violation for that date.
- Unknown
type→ValueErrorraised immediately.
Reference Solution
from collections import defaultdict
from typing import Dict, List
DEFAULT_NAMES = {
"receipt_required": "ReceiptRequiredRule",
"daily_category_cap": "DailyCategoryCapRule",
"mutual_exclusion": "MutualExclusionRule",
}
def check_spending_report(entries: List[Dict], policies: List[Dict]) -> List[Dict]:
violations = []
for policy in policies:
kind = policy["type"]
if kind not in DEFAULT_NAMES:
raise ValueError(f"Unknown rule type: {kind}")
name = policy.get("rule_name", DEFAULT_NAMES[kind])
if kind == "receipt_required":
categories = set(policy["categories"])
threshold = policy["threshold"]
for entry in entries:
if (
entry["category"] in categories
and entry["amount"] > threshold
and not entry["has_receipt"]
):
violations.append({
"rule_name": name,
"message": (
f'{entry["category"]} expense exceeds {threshold}'
f' and requires a receipt'
),
"item_ids": [entry["id"]],
})
elif kind == "daily_category_cap":
category = policy["category"]
limit = policy["daily_limit"]
groups: Dict = defaultdict(list)
for entry in entries:
if entry["category"] == category:
groups[entry["expense_date"]].append(entry)
for day in sorted(groups):
group = groups[day]
total = sum(e["amount"] for e in group)
if total > limit:
violations.append({
"rule_name": name,
"message": (
f'{category} expenses on {day} total {total:g},'
f' exceeding daily limit {limit:g}'
),
"item_ids": [e["id"] for e in group],
})
elif kind == "mutual_exclusion":
category_a = policy["category_a"]
category_b = policy["category_b"]
dates_a: Dict = defaultdict(list)
dates_b: Dict = defaultdict(list)
for entry in entries:
if entry["category"] == category_a:
dates_a[entry["expense_date"]].append(entry)
if entry["category"] == category_b:
dates_b[entry["expense_date"]].append(entry)
for day in sorted(dates_a.keys() & dates_b.keys()):
ids = (
[e["id"] for e in dates_a[day]]
+ [e["id"] for e in dates_b[day]]
)
violations.append({
"rule_name": name,
"message": (
f'{category_a} and {category_b} expenses cannot'
f' both appear on {day}'
),
"item_ids": ids,
})
return violations