KatInterview

Boolean Condition Trees for a Spending Policy Checker

Data Structure DesignModel answer
HardModel answerData Structure Designexpression-treerules-enginevalidation

Last updated

Design a data-driven policy engine whose rules combine field checks with nested AND, OR and NOT, covering representation, validation, missing-field behavior and explainable results.

You maintain a service that checks employee expenses against company spending policies. Today each policy is a single flat check. You are asked to let policies combine checks using nested AND, OR and NOT.

Policies must be expressible for cases like:

  • The expense category is "restaurant", the expense type is "meals", and the amount is greater than 50.
  • Either (the category is "entertainment" and the amount is greater than 100), or the expense is tagged as client hosting.
  • The amount is greater than 100 and the vendor name is not equal to a given supplier.

Policies are submitted to the service as data through an API. They must never be executed as arbitrary code.

Describe your design and sketch an implementation. Cover:

  1. How you represent a condition, including both the combining nodes and the leaf checks.
  2. How you validate a policy when it is created, and what you reject.
  3. How you evaluate a policy against an expense, including what happens when a field is missing.
  4. How the engine reports which part of a policy caused a violation.
  5. How you would add new fields or operators later without rewriting the evaluator.

State your assumptions explicitly. In particular, decide which expense field each business term maps to, which operators are supported, whether an empty AND or OR is legal, what limits you place on depth and size, and whether composite conditions select individual expenses before any group-level aggregation (such as a per-trip total) is applied.

Hints

Hint 1

Model a condition as a small tagged tree: composite nodes (AND, OR, NOT) hold child conditions, and leaf nodes hold a field, an operator and a value. Evaluation is a simple recursion over this tree.

Hint 2

Do the hard work at creation time: check that fields exist, that each operator is legal for the field's type, that the value has the right type, that NOT has exactly one child, and that depth and node count are bounded. Evaluation then stays trivial and safe.

Hint 3

Decide missing-field behavior once and write it down. A common choice is that a leaf on a missing field evaluates to false (or to an explicit 'unknown'), so that NOT of a missing-field check does not silently pass. Also return a result tree, not just a boolean, so you can explain why a rule fired.