Data-Driven Fare Policy Rule Engine
Arrays & HashingAuto-graded · 17 test casesLast updated
Evaluate stored fare and per-driver policy rules over a trip table with generic field/operator conditions and exact integer-cent sums.
A trip-audit system must report which trips and which drivers break finance-defined payout policies. Policies arrive as plain table rows — nothing about a policy may be baked into code — so the evaluator must interpret conditions generically.
Write audit_fare_policies(trips, policies, conditions) -> List[List[str]].
Input contract
All money is held as whole cents (integers), never floats, so repeated additions stay exact.
trips: each row is[tripId, driverId, amountCents, tripType, zoneType, zoneName]. Trip IDs are unique and every column is populated. At most 10,000 rows.amountCentsis a nonnegative integer written as a string, no larger than 100,000,000.policies: each row is[policyId, scope, limitCents], andpolicyIdvalues are unique.scopeis either"FARE"or"DRIVER_SUM". For"FARE",limitCentsis the empty string and is ignored. For"DRIVER_SUM",limitCentsis a nonnegative integer written as a string. At most 100 policies.conditions: each row is[policyId, field, operator, value], at most 1,000 rows. All conditions listed under the samepolicyIdare combined with AND. A policy that has no conditions matches every trip. Every condition'spolicyIdrefers to a policy that exists.- Allowed
fieldnames:fare_id,driver_id,amount_cents,fare_type,zone_type,zone_name. - When
fieldisamount_cents, both sides are compared as integers andoperatormay beEQ,NE,GT,GE,LT, orLE. For every other field onlyEQandNEare used, and comparison is exact and case-sensitive on the strings. - Input is always well formed.
Output contract
Produce one row [scope, subjectId, policyId, actualCents] per violation, where subjectId is a trip ID (for "FARE" policies) or a driver ID (for "DRIVER_SUM" policies), and actualCents is that trip's amount or the driver's filtered total, written as an integer string.
Grouping and order:
- Policies are emitted in the order given in
policies. - Inside a
"FARE"policy, a violating trip is emitted for every trip that satisfies all its conditions, in trip input order. - Inside a
"DRIVER_SUM"policy, first total theamountCentsof that policy's matching trips separately per driver, then emit a row only for drivers whose total is strictly greater thanlimitCents. Within such a policy, drivers appear in ascending (lexicographic)driverIdorder. - A driver with no matching trips has total zero and is never emitted, since limits are nonnegative.
Examples
Example 1
Input: audit_fare_policies([['F1', 'D1', '1200', 'airport', 'surge', 'downtown'], ['F2', 'D1', '900', 'standard', 'normal', 'suburb'], ['F3', 'D2', '5000', 'airport', 'normal', 'downtown'], ['F4', 'D2', '300', 'standard', 'normal', 'suburb'], ['F5', 'D1', '2200', 'airport', 'surge', 'downtown']], [['R1', 'FARE', ''], ['R2', 'DRIVER_SUM', '3000']], [['R1', 'fare_type', 'EQ', 'airport'], ['R1', 'amount_cents', 'GT', '1000'], ['R2', 'zone_type', 'EQ', 'surge']])
Output: [['FARE', 'F1', 'R1', '1200'], ['FARE', 'F3', 'R1', '5000'], ['FARE', 'F5', 'R1', '2200'], ['DRIVER_SUM', 'D1', 'R2', '3400']]
Hints
Hint 1
Store each policy's conditions keyed by policyId once up front, then a trip either satisfies all of them or fails on the first mismatch.
Hint 2
Write a single matching routine that handles both numeric and string fields by choosing the comparison from the field name — do not special-case individual policies.
Hint 3
The only real branching is on scope: one pass appending trips, versus one pass accumulating integer totals into a per-driver dict followed by a sorted scan with a strict `>` test.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The point of the task is that no policy may be hard-coded: the engine has exactly one code path per scope, and everything policy-specific lives in the input data.
- Index the conditions once. Build a map from
policyIdto its list of condition tuples, resolving each field name to a column position with a small fixed dictionary. A policy missing from the map is treated as having no conditions, which by the contract matches every trip. - One generic match test. For a trip and a policy, walk that policy's conditions and stop at the first failure. When the field is
amount_cents, compare the pre-parsed integer amount against the parsed integer value using the six numeric operators; otherwise compare the raw strings withEQ/NE. The per-trip amount is parsed once for the whole run rather than on every comparison. - Aggregate per scope.
"FARE"policies simply append every matching trip in a single pass over the input, which preserves trip order for free."DRIVER_SUM"policies accumulate an integer total per driver (in adefaultdict(int), never a float) over matching trips, then walk the drivers in sorted order and emit those whose total is strictly greater than the parsed limit.
Why it is correct
Each emitted row comes from exactly one policy that a trip (or driver) fully satisfies: conditions are AND-ed by the early-return loop, so a row appears only if every condition holds. A policy with no conditions yields an empty condition list and so matches everything, which is the required default. For "DRIVER_SUM", the total is a plain integer sum over precisely the matching trips for that driver, and the strict > comparison plus the nonnegative limit guarantees that drivers with no matching trips (absent from the map) are never emitted. Ordering is respected because policies are iterated in input order, fare rows are visited once in input order, and driver IDs are sorted before emission.
Complexity
Let F, P, C be the counts of trips, policies, and conditions. Grouping conditions costs O(C). Evaluation is at most O(P · F · c), where c is the largest number of conditions on one policy; summing over policies this is bounded by O(F · C) in the worst case. Sorting the matched drivers within each "DRIVER_SUM" policy adds O(d log d) for d distinct drivers under that policy. Space is O(C + F) for the grouped conditions and the per-driver totals, comfortably within the given bounds.
from collections import defaultdict
from typing import List
def audit_fare_policies(trips: List[List[str]], policies: List[List[str]], conditions: List[List[str]]) -> List[List[str]]:
column = {
"fare_id": 0,
"driver_id": 1,
"amount_cents": 2,
"fare_type": 3,
"zone_type": 4,
"zone_name": 5,
}
def num_cmp(op, a, b):
if op == "EQ":
return a == b
if op == "NE":
return a != b
if op == "GT":
return a > b
if op == "GE":
return a >= b
if op == "LT":
return a < b
return a <= b
def str_cmp(op, a, b):
return a == b if op == "EQ" else a != b
by_policy = defaultdict(list)
for policy_id, field, operator, value in conditions:
by_policy[policy_id].append((column[field], field, operator, value))
parsed = [(trip, int(trip[2])) for trip in trips]
def satisfies(trip, amount, policy_id):
for idx, field, operator, value in by_policy.get(policy_id, ()):
if field == "amount_cents":
if not num_cmp(operator, amount, int(value)):
return False
else:
if not str_cmp(operator, trip[idx], value):
return False
return True
out = []
for policy_id, scope, limit_cents in policies:
if scope == "FARE":
for trip, amount in parsed:
if satisfies(trip, amount, policy_id):
out.append([scope, trip[0], policy_id, str(amount)])
else:
totals = defaultdict(int)
for trip, amount in parsed:
if satisfies(trip, amount, policy_id):
totals[trip[1]] += amount
limit = int(limit_cents)
for driver_id in sorted(totals):
if totals[driver_id] > limit:
out.append([scope, driver_id, policy_id, str(totals[driver_id])])
return out