KatInterview

Rule Engine with Operator Precedence and Quoted Strings

StringsModel answer
MediumModel answerStringsparsingstring-matchingoperator-precedence

Last updated

Build a transaction filter that evaluates accept/block rules in sequence, supporting field equality, boolean logic, AND/OR operators, and parentheses.

You're building a rule-based transaction filter. Given a transaction represented as a dictionary and an ordered list of rules, determine whether to accept or block the transaction.

Core behavior:

  • Rules are checked top-to-bottom; the first matching rule determines the outcome
  • Each rule is a tuple (condition, outcome) where outcome is "accept" or "block"
  • If no rules match, default to "accept"
  • All inputs are well-formed

Example:

transaction = {"merchant": "Corner Store", "country": "US"}
rules = [
    ('country == "FR"', "block"),
    ('merchant == "Corner Store"', "accept"),
]
evaluate(transaction, rules)  # Returns "accept"

Implement this in three progressive stages:

Stage 1: Basic equality Handle conditions comparing one field to one string literal using ==. String literals appear in double quotes. Either operand order should work (field == literal or literal == field).

Stage 2: Boolean logic Add support for:

  • Boolean field checks (fields that hold true/false values)
  • AND and OR operators combining conditions
  • Proper tokenization so strings containing "and" or "or" don't break parsing
  • Standard precedence: AND binds tighter than OR

Stage 3: Parentheses Support arbitrary nesting of conditions with parentheses to override precedence.

Example: (country == "US" OR country == "CA") AND merchant == "Corner Store"

Clarifications needed:

  • How should missing fields be handled in comparisons?
  • Are operators case-sensitive?
  • How are quotes escaped within string literals?
  • How are boolean values represented in conditions?

Hints

Hint 1

Separate tokenization from parsing—handle quoted strings as single tokens first

Hint 2

Keep each stage's tests passing as you add features; first-match semantics must survive

Hint 3

For precedence, consider recursive descent parsing or converting to postfix notation