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:

  1. All-conditions match: A rule triggers if and only if every tag in rule["conditions"] is present in permit_conditions (an empty "conditions" collection triggers unconditionally; duplicate tags have no extra effect).
  2. Override priority: Whenever multiple rules trigger on the same application, return the highest-ranked status under "REJECTED" (rank 2) > "APPROVED" (rank 1) > "PENDING" (rank 0), regardless of rule order in rules.
  3. Fallback status: When zero rules trigger (including when rules is 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,000
  • 0 <= len(permit_conditions) <= 50
  • Each rule["conditions"] has 0 to 50 case-sensitive string tags.
  • Valid outcomes are "REJECTED" (rank 2), "APPROVED" (rank 1), and "PENDING" (rank 0).

Step-by-step walkthrough

  1. Understand the inputs, matching rule, and precedence

    We receive a list of decision rules together with an application's active permit_conditions, and we must return "REJECTED", "APPROVED", or "PENDING".

    • Input shapes: Each rule is a dictionary {"conditions": [...], "outcome": "..."}. Both rule["conditions"] and permit_conditions can 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 inside permit_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 PermitProcessor class and invoke it from get_permit_status(rules, permit_conditions).

  2. Why naive list scans and string comparisons fall short

    Two subtle bugs catch candidates who jump straight to code:

    1. 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)
    
    1. Repeated list scans waste work: Testing tag in permit_conditions while permit_conditions is a list scans up to 50 strings linearly for every tag of every rule. Converting permit_conditions into a Python set once at the start turns each membership check into an O(1) average hash lookup.

    With up to 1,000 rules and 50 tags per rule, one pass over sets and integer ranks completes in microseconds.

  3. Precompute rule sets in PermitProcessor.__init__

    Inside __init__, validate each rule's "outcome" immediately (raising ValueError on an unknown status) and store each rule's "conditions" as a frozenset (an immutable hash set). Precomputing frozenset objects once in __init__ avoids rebuilding rule sets whenever a single PermitProcessor scores 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))
    
  4. Evaluate a permit in one pass with early exit

    Inside get_status(permit_conditions):

    1. Build active_conditions = set(permit_conditions) once.
    2. 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) is False, leaving best_status untouched unless a higher-ranked rule also triggers.
    3. For each (required_conditions, outcome) in self.rules, check required_conditions.issubset(active_conditions). When it holds and PRIORITY[outcome] > PRIORITY[best_status], upgrade best_status.
    4. As soon as best_status == "REJECTED", break immediately — nothing can outrank 2.
        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
    
  5. Trace the three examples step by step

    Let's walk get_status through 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"
    
  6. Complete solution

    Wrapping PermitProcessor inside get_permit_status gives 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 to get_permit_status (or O(S) once in __init__ and O(S + P) worst-case per get_status call when reusing PermitProcessor). Building the frozenset (an immutable hash set) for each rule reads all S rule strings once; building active_conditions reads all P application strings once; and testing required_conditions.issubset(active_conditions) performs at most |required_conditions| O(1) average hash lookups per rule, stopping early as soon as any REJECTED rule triggers or any missing tag is encountered.
  • Space: O(S + P). self.rules stores all deduplicated rule tags (O(S)), and active_conditions holds at most P application tags during evaluation.

Edge cases

  • Empty rules list (rules = []): Zero rules trigger, so best_status stays 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 PENDING rule: When {"intake_done"} -> "PENDING" triggers, PRIORITY["PENDING"] > PRIORITY["PENDING"] (0 > 0) is False, so best_status stays "PENDING" unless an APPROVED or REJECTED rule 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 PRIORITY inside __init__ fails fast with ValueError even if an early REJECTED exit skips later rules during get_status.

Common mistakes

  • Returning on the first matching rule: That makes the output depend on rule order and fails Example 1, where an APPROVED rule precedes a REJECTED rule. Only a REJECTED match can exit early.
  • Comparing status strings alphabetically (outcome > best_status): Alphabetically "REJECTED" > "PENDING" > "APPROVED", so "PENDING" beats "APPROVED". Always compare PRIORITY[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_conditions on a list: Turns each tag lookup into an O(P) scan instead of O(1).
  • Returning None when nothing matches: Applications with zero matching rules must default to "PENDING".

Alternative approaches

  • Bucket rules by outcome in __init__: Partition rules into self.rejected_rules and self.approved_rules (discarding PENDING rules completely since they can never change the "PENDING" fallback). In get_status, check self.rejected_rules first and return "REJECTED" on the first match, then check self.approved_rules and return "APPROVED" on the first match, otherwise return "PENDING". Same O(S + P) worst-case bound, with even faster early exits when REJECTED rules 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 Python int bitmask (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 all PENDING rules (since they never change the "PENDING" fallback), prune dominated rules whose required tags are supersets of an equally ranked or higher-ranked rule, and check REJECTED rules before APPROVED rules 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 with P tags, increment per-rule hit counters along only those P posting lists, and any rule whose counter reaches len(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_mode attribute ("ALL" or "ANY", or small matcher objects) on each compiled rule and encapsulate the predicate inside rule_matches(active_conditions). An "ALL" rule checks required_conditions.issubset(active_conditions), whereas an "ANY" rule checks not 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 in get_status remains unchanged.
  • What changes would you make to expose an audit trace identifying the exact rule(s) responsible for a REJECTED result? Record each rule's index or unique rule_id alongside (required_conditions, outcome) in self.rules and update winning_rule_id whenever best_status advances. Expose a companion explain_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 early break on "REJECTED" and collect every matching "REJECTED" rule_id (plus its matched required_conditions) in order.

Follow-up questions

Similar questions

More Permitflow interview questions

All 1 Permitflow questions →