Permit Status Rule Evaluator
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A municipal licensing engine decides the status of an application by checking its active attribute tags against a list of decision rules. Every evaluation produces one of three status strings: "REJECTED", "APPROVED", or "PENDING".
Implement get_permit_status(rules, permit_conditions) (optionally backed by a reusable PermitProcessor class with __init__(self, rules) and get_status(self, permit_conditions)):
def get_permit_status(
rules: List[Dict[str, object]], permit_conditions: List[str]
) -> str:
Each entry in rules is a dictionary with two keys:
- "conditions": an iterable (such as a list or set) of case-sensitive string tags required by that rule.
- "outcome": one of "REJECTED", "APPROVED", or "PENDING".
Evaluate permit_conditions (an iterable of case-sensitive string tags attached to the application) using these rules:
- All-conditions match: A rule triggers if and only if every tag in
rule["conditions"]is present inpermit_conditions(an empty"conditions"collection triggers unconditionally; duplicate tags have no extra effect). - Override priority: Whenever multiple rules trigger on the same application, return the highest-ranked status under
"REJECTED"(rank2) >"APPROVED"(rank1) >"PENDING"(rank0), regardless of rule order inrules. - Fallback status: When zero rules trigger (including when
rulesis empty), return"PENDING".
Examples
Example 1
Input:
rules = [
{"conditions": ["site_plan", "fee_cleared"], "outcome": "APPROVED"},
{"conditions": ["stop_work_order"], "outcome": "REJECTED"},
]
permit_conditions = ["site_plan", "fee_cleared", "stop_work_order"]
Output:
"REJECTED"
Explanation: Both rules trigger because {"site_plan", "fee_cleared"} and {"stop_work_order"} are contained in permit_conditions. "REJECTED" outranks "APPROVED", so "REJECTED" is returned.
Example 2
Input:
rules = [
{"conditions": ["structural_signoff", "fire_review"], "outcome": "APPROVED"},
]
permit_conditions = ["structural_signoff"]
Output:
"PENDING"
Explanation: The rule requires both "structural_signoff" and "fire_review", so missing "fire_review" prevents it from triggering. With zero triggered rules, the status falls back to "PENDING".
Example 3
Input:
rules = [
{"conditions": ["intake_done"], "outcome": "PENDING"},
{"conditions": ["intake_done", "electrical_ok"], "outcome": "APPROVED"},
{"conditions": ["expired_license"], "outcome": "REJECTED"},
]
permit_conditions = ["intake_done", "electrical_ok"]
Output:
"APPROVED"
Explanation: The first two rules trigger ("PENDING" and "APPROVED"), while the third rule does not because "expired_license" is absent. Between "PENDING" and "APPROVED", "APPROVED" has higher priority.
Constraints
0 <= len(rules) <= 1,0000 <= len(permit_conditions) <= 50- Each
rule["conditions"]has0to50case-sensitive string tags. - Valid outcomes are
"REJECTED"(rank2),"APPROVED"(rank1), and"PENDING"(rank0).
Step-by-step walkthrough
Understand the inputs, matching rule, and precedence
We receive a list of decision
rulestogether with an application's activepermit_conditions, and we must return"REJECTED","APPROVED", or"PENDING".- Input shapes: Each rule is a dictionary
{"conditions": [...], "outcome": "..."}. Bothrule["conditions"]andpermit_conditionscan arrive as lists or sets of case-sensitive strings. - When a rule triggers (subset test): A rule triggers if every tag in
rule["conditions"]appears insidepermit_conditions. Extra tags on the application never hurt, whereas missing even a single required tag prevents a match:
Application tags: {"site_plan", "fee_cleared"} Rule A needs {"site_plan"} -> ALL present -> TRIGGERS Rule B needs {"site_plan", "fee_cleared"} -> ALL present -> TRIGGERS Rule C needs {"site_plan", "fire_review"} -> missing "fire_review" -> NO MATCH Rule D needs {} (empty set) -> 0 missing tags -> ALWAYS TRIGGERS- How conflicts resolve: Multiple rules can trigger on the same application. When that happens, the strongest status wins regardless of rule order:
REJECTED>APPROVED>PENDING - Fallback: When zero rules trigger, return
"PENDING".
We organize the evaluation inside a reusable
PermitProcessorclass and invoke it fromget_permit_status(rules, permit_conditions).- Input shapes: Each rule is a dictionary
Why naive list scans and string comparisons fall short
Two subtle bugs catch candidates who jump straight to code:
- Alphabetical string comparison gets the order backwards: Comparing status strings directly (
max(outcome, best_status)) uses ASCII order:"APPROVED" < "PENDING" < "REJECTED"('A' < 'P' < 'R'). That wrongly lets"PENDING"beat"APPROVED"! Instead, assign each status an explicit integer rank:
"PENDING" -> 0 (lowest rank, and also the fallback status) "APPROVED" -> 1 "REJECTED" -> 2 (highest rank)- Repeated list scans waste work: Testing
tag in permit_conditionswhilepermit_conditionsis alistscans up to50strings linearly for every tag of every rule. Convertingpermit_conditionsinto a Pythonsetonce at the start turns each membership check into anO(1)average hash lookup.
With up to
1,000rules and50tags per rule, one pass over sets and integer ranks completes in microseconds.- Alphabetical string comparison gets the order backwards: Comparing status strings directly (
Precompute rule sets in PermitProcessor.__init__
Inside
__init__, validate each rule's"outcome"immediately (raisingValueErroron an unknown status) and store each rule's"conditions"as afrozenset(an immutable hash set). Precomputingfrozensetobjects once in__init__avoids rebuilding rule sets whenever a singlePermitProcessorscores many applications.from typing import Any, Dict, List, Optional, Set, Tuple # Numeric rank for each status so integer comparison enforces REJECTED > APPROVED > PENDING # (plain alphabetical comparison would wrongly rank "PENDING" above "APPROVED"). PRIORITY: Dict[str, int] = { "PENDING": 0, "APPROVED": 1, "REJECTED": 2, } class PermitProcessor: def __init__(self, rules: List[Dict[str, object]]) -> None: # self.rules: list of (required_conditions_frozenset, outcome_str), # e.g. [(frozenset({"site_plan", "fee_cleared"}), "APPROVED"), (frozenset({"stop_work_order"}), "REJECTED")]. # Precomputing frozensets once lets many permits reuse the same processor cheaply. self.rules: List[Tuple[frozenset, str]] = [] for rule in rules: outcome = str(rule["outcome"]) if outcome not in PRIORITY: raise ValueError(f"unknown outcome: {outcome!r}") required_conditions = frozenset(rule["conditions"]) self.rules.append((required_conditions, outcome))Evaluate a permit in one pass with early exit
Inside
get_status(permit_conditions):- Build
active_conditions = set(permit_conditions)once. - Start with
best_status = "PENDING". If zero rules trigger,"PENDING"is already our answer; if a"PENDING"rule triggers,PRIORITY["PENDING"] > PRIORITY["PENDING"](0 > 0) isFalse, leavingbest_statusuntouched unless a higher-ranked rule also triggers. - For each
(required_conditions, outcome)inself.rules, checkrequired_conditions.issubset(active_conditions). When it holds andPRIORITY[outcome] > PRIORITY[best_status], upgradebest_status. - As soon as
best_status == "REJECTED",breakimmediately — nothing can outrank2.
def get_status(self, permit_conditions: List[str]) -> str: # Phase 1: Convert permit conditions to a hash set once for O(1) average lookups. active_conditions = set(permit_conditions) # Phase 2: Default to "PENDING" (rank 0), which applies when zero rules match. best_status = "PENDING" # Phase 3: Check each rule; keep the highest-priority outcome among all subset matches. for required_conditions, outcome in self.rules: # Equivalent to required_conditions <= active_conditions: ALL required items must be present. if required_conditions.issubset(active_conditions): if PRIORITY[outcome] > PRIORITY[best_status]: best_status = outcome # Nothing can outrank REJECTED (rank 2), so we can stop scanning immediately. if best_status == "REJECTED": break return best_status- Build
Trace the three examples step by step
Let's walk
get_statusthrough Examples 1, 2, and 3:Example 1: active_conditions = {"site_plan", "fee_cleared", "stop_work_order"}, best_status = "PENDING" (0) Rule 1: {"site_plan", "fee_cleared"} -> "APPROVED" (1) subset is True; 1 > 0 -> best_status = "APPROVED" Rule 2: {"stop_work_order"} -> "REJECTED" (2) subset is True; 2 > 1 -> best_status = "REJECTED" (break!) Result: "REJECTED" Example 2: active_conditions = {"structural_signoff"}, best_status = "PENDING" (0) Rule 1: {"structural_signoff", "fire_review"} -> "APPROVED" (1) missing "fire_review" -> subset is False Result: "PENDING" Example 3: active_conditions = {"intake_done", "electrical_ok"}, best_status = "PENDING" (0) Rule 1: {"intake_done"} -> "PENDING" (0) subset is True, 0 > 0 is False -> best_status stays "PENDING" Rule 2: {"intake_done", "electrical_ok"} -> "APPROVED" (1) subset is True, 1 > 0 is True -> best_status = "APPROVED" Rule 3: {"expired_license"} -> "REJECTED" (2) missing "expired_license" -> subset is False Result: "APPROVED"Complete solution
Wrapping
PermitProcessorinsideget_permit_statusgives the complete solution:from typing import Any, Dict, List, Optional, Set, Tuple # Numeric rank for each status so integer comparison enforces REJECTED > APPROVED > PENDING # (plain alphabetical comparison would wrongly rank "PENDING" above "APPROVED"). PRIORITY: Dict[str, int] = { "PENDING": 0, "APPROVED": 1, "REJECTED": 2, } class PermitProcessor: def __init__(self, rules: List[Dict[str, object]]) -> None: # self.rules: list of (required_conditions_frozenset, outcome_str), # e.g. [(frozenset({"site_plan", "fee_cleared"}), "APPROVED"), (frozenset({"stop_work_order"}), "REJECTED")]. # Precomputing frozensets once lets many permits reuse the same processor cheaply. self.rules: List[Tuple[frozenset, str]] = [] for rule in rules: outcome = str(rule["outcome"]) if outcome not in PRIORITY: raise ValueError(f"unknown outcome: {outcome!r}") required_conditions = frozenset(rule["conditions"]) self.rules.append((required_conditions, outcome)) def get_status(self, permit_conditions: List[str]) -> str: # Phase 1: Convert permit conditions to a hash set once for O(1) average lookups. active_conditions = set(permit_conditions) # Phase 2: Default to "PENDING" (rank 0), which applies when zero rules match. best_status = "PENDING" # Phase 3: Check each rule; keep the highest-priority outcome among all subset matches. for required_conditions, outcome in self.rules: # Equivalent to required_conditions <= active_conditions: ALL required items must be present. if required_conditions.issubset(active_conditions): if PRIORITY[outcome] > PRIORITY[best_status]: best_status = outcome # Nothing can outrank REJECTED (rank 2), so we can stop scanning immediately. if best_status == "REJECTED": break return best_status def get_permit_status( rules: List[Dict[str, object]], permit_conditions: List[str] ) -> str: processor = PermitProcessor(rules) return processor.get_status(permit_conditions)✅ Submit now — all tests should pass.
Intuition & how it works
Picture a licensing clerk checking a folder of attribute tags against a binder of checklists. Each checklist says: "When every tag on this checklist appears in the folder, stamp this status." Because several checklists can fire on the same application — for instance, {"site_plan", "fee_cleared"} -> APPROVED alongside {"stop_work_order"} -> REJECTED — the clerk resolves clashes with an override rank where REJECTED overrides APPROVED, and APPROVED overrides PENDING. Formally, each checklist check is a subset test (set A is a subset of set B when every element of A belongs to B), and clash resolution picks the highest integer rank (REJECTED: 2 > APPROVED: 1 > PENDING: 0).
Why do tempting shortcuts fail? Returning the first triggered rule breaks whenever an APPROVED rule precedes a matching REJECTED rule in rules (as in Example 1). Comparing status strings directly with max() also breaks because ASCII order places "PENDING" above "APPROVED" ('P' > 'A'). And leaving permit_conditions as a plain Python list repeats a linear scan on every tag check instead of doing an O(1) lookup in a hash set (a collection that uses keys' hash values to test membership in constant average time).
Here is a walkthrough with permit_conditions = ["site_plan", "fee_cleared", "stop_work_order"] and three rules:
active_conditions = {"site_plan", "fee_cleared", "stop_work_order"}, best_status = "PENDING" (rank 0)
1. Rule {"site_plan", "fee_cleared"} -> "APPROVED" (rank 1):
Both required tags are in active_conditions -> MATCH!
Rank 1 > 0 -> best_status becomes "APPROVED".
2. Rule {"site_plan", "fire_review"} -> "APPROVED" (rank 1):
"fire_review" is missing from active_conditions -> NO MATCH.
3. Rule {"stop_work_order"} -> "REJECTED" (rank 2):
Required tag is in active_conditions -> MATCH!
Rank 2 > 1 -> best_status becomes "REJECTED" (top possible rank -> stop early!).
Complexity
Let S be the total number of condition strings across all R rules, and let P be the number of condition strings on the application.
- Time:
O(S + P)average for a single call toget_permit_status(orO(S)once in__init__andO(S + P)worst-case perget_statuscall when reusingPermitProcessor). Building thefrozenset(an immutable hash set) for each rule reads allSrule strings once; buildingactive_conditionsreads allPapplication strings once; and testingrequired_conditions.issubset(active_conditions)performs at most|required_conditions|O(1)average hash lookups per rule, stopping early as soon as anyREJECTEDrule triggers or any missing tag is encountered. - Space:
O(S + P).self.rulesstores all deduplicated rule tags (O(S)), andactive_conditionsholds at mostPapplication tags during evaluation.
Edge cases
- Empty
ruleslist (rules = []): Zero rules trigger, sobest_statusstays at its initial value"PENDING". - Rule with empty conditions (
{"conditions": [], "outcome": "APPROVED"}): In set theory, the empty set is a subset of every set (even of an empty application[]), because zero required tags are missing. That rule always triggers. - Partial overlap does not trigger: A rule requiring
{"structural_signoff", "fire_review"}does not match an application that only has{"structural_signoff"}(Example 2). - Matching
PENDINGrule: When{"intake_done"} -> "PENDING"triggers,PRIORITY["PENDING"] > PRIORITY["PENDING"](0 > 0) isFalse, sobest_statusstays"PENDING"unless anAPPROVEDorREJECTEDrule also triggers (Example 3). - Duplicate strings or set inputs: Duplicate tag names collapse automatically when converted to sets, and
frozenset(...)/set(...)accept lists, tuples, or sets alike. - Case sensitivity:
"Paid"and"paid"are distinct strings and do not match each other. - Invalid outcome strings: Validating
outcome in PRIORITYinside__init__fails fast withValueErroreven if an earlyREJECTEDexit skips later rules duringget_status.
Common mistakes
- Returning on the first matching rule: That makes the output depend on rule order and fails Example 1, where an
APPROVEDrule precedes aREJECTEDrule. Only aREJECTEDmatch can exit early. - Comparing status strings alphabetically (
outcome > best_status): Alphabetically"REJECTED" > "PENDING" > "APPROVED", so"PENDING"beats"APPROVED". Always comparePRIORITY[outcome]. - Checking set intersection instead of subset: Testing
bool(required_conditions & active_conditions)checks whether at least one tag is present rather than every required tag. - Testing
tag in permit_conditionson a list: Turns each tag lookup into anO(P)scan instead ofO(1). - Returning
Nonewhen nothing matches: Applications with zero matching rules must default to"PENDING".
Alternative approaches
- Bucket rules by outcome in
__init__: Partition rules intoself.rejected_rulesandself.approved_rules(discardingPENDINGrules completely since they can never change the"PENDING"fallback). Inget_status, checkself.rejected_rulesfirst and return"REJECTED"on the first match, then checkself.approved_rulesand return"APPROVED"on the first match, otherwise return"PENDING". SameO(S + P)worst-case bound, with even faster early exits whenREJECTEDrules exist. - Integer bitmasks: When the vocabulary of distinct tag names is modest, map each unique tag to a bit position
1 << i. Every rule and application becomes a single Pythonintbitmask (an integer whose binary bits encode set membership), shrinking each subset check to(rule_mask & active_mask) == rule_mask.
Follow-up questions
- How would you speed up evaluation when scoring one million permit applications against a fixed rule list? Instantiate
PermitProcessor(rules)once up front, drop allPENDINGrules (since they never change the"PENDING"fallback), prune dominated rules whose required tags are supersets of an equally ranked or higher-ranked rule, and checkREJECTEDrules beforeAPPROVEDrules so early exit fires immediately. If the tag vocabulary is compact, encode rules and applications as integer bitmasks so each subset test is one bitwise operation(rule_mask & active_mask) == rule_mask. When thousands of sparse rules draw from a huge tag vocabulary, build an inverted index (a map from each tag string to the rule IDs requiring it): for an application withPtags, increment per-rule hit counters along only thosePposting lists, and any rule whose counter reacheslen(rule)matched without touching unrelated rules. - How would you adapt the design if rules could specify an 'any-of' condition match alongside the existing 'all-of' requirement? Store a
match_modeattribute ("ALL"or"ANY", or small matcher objects) on each compiled rule and encapsulate the predicate insiderule_matches(active_conditions). An"ALL"rule checksrequired_conditions.issubset(active_conditions), whereas an"ANY"rule checksnot required_conditions.isdisjoint(active_conditions)(true whenever the two sets share at least one tag; note that an empty"ANY"set matches nothing while an empty"ALL"set matches everything). The precedence loop inget_statusremains unchanged. - What changes would you make to expose an audit trace identifying the exact rule(s) responsible for a
REJECTEDresult? Record each rule's index or uniquerule_idalongside(required_conditions, outcome)inself.rulesand updatewinning_rule_idwheneverbest_statusadvances. Expose a companionexplain_status(permit_conditions)method (or an optional flag): if callers want a single winning trigger, return(best_status, winning_rule_id); if compliance reviewers need all rejection reasons, disable the earlybreakon"REJECTED"and collect every matching"REJECTED"rule_id(plus its matchedrequired_conditions) in order.
Follow-up questions
- How would you speed up evaluation when scoring one million permit applications against a fixed rule list?
- How would you adapt the design if rules could specify an 'any-of' condition match alongside the existing 'all-of' requirement?
- What changes would you make to expose an audit trace identifying the exact rule(s) responsible for a `REJECTED` result?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array