Match Documents Against Filter Expressions
Trees & GraphsAuto-graded · 20 test casesLast updated
Build a recursive evaluator for filter expressions with logical operators and field comparisons, testing tree traversal and nested field lookup.
You're building a component that determines whether data records satisfy filter criteria. Filter criteria are represented as nested expression trees, and you need to evaluate them against candidate records.
Write a function that accepts a filter expression and a data record, returning whether the record satisfies the filter.
Filter Expression Structure
A filter expression is a dictionary that can be either a logical operator node or a comparison node.
Logical Operator Nodes
{"$and": [expr_1, expr_2, ...]}— ReturnsTruewhen every sub-expression returnsTrue. An empty list returnsTrue.{"$or": [expr_1, expr_2, ...]}— ReturnsTruewhen at least one sub-expression returnsTrue. An empty list returnsFalse.{"$not": expr}— Returns the opposite of the sub-expression's result.
Comparison Nodes
{"field": str, "op": str, "val": any}
The field specifies which record field to examine. Nested fields use dot notation: "user.profile.email" accesses record["user"]["profile"]["email"].
The op specifies the comparison:
"$eq"— field value equalsval"$ne"— field value does not equalval"$gt"— field value is greater thanval"$gte"— field value is greater than or equal toval"$lt"— field value is less thanval"$lte"— field value is less than or equal toval"$in"— field value appears inval(wherevalis a list)
Missing Fields
When a field path doesn't exist in the record:
- All comparison operations return
False, except "$ne"returnsTrue
A path is considered missing if any intermediate step fails (e.g., accessing "a.b" when "a" contains a non-dictionary value, or when a key doesn't exist).
Constraints
- Expression tree depth ≤ 100
- Field paths contain only alphanumeric characters and dots
- Comparison operations
$gt,$gte,$lt,$lteare only applied to comparable types - All expressions are well-formed according to the specification
Examples
Example 1
Input: match_filter({'$and': [{'field': 'age', 'op': '$gte', 'val': 18}, {'field': 'status', 'op': '$eq', 'val': 'active'}]}, {'name': 'Alice', 'age': 22, 'status': 'active'})
Output: True
Example 2
Input: match_filter({'$or': [{'field': 'user.role', 'op': '$in', 'val': ['admin', 'moderator']}, {'$not': {'field': 'user.banned', 'op': '$eq', 'val': True}}]}, {'user': {'role': 'guest', 'banned': False}})
Output: True
Hints
Hint 1
Use a sentinel object to distinguish missing fields from fields with None values
Hint 2
Handle logical operators recursively, letting Python's all() and any() manage empty lists and short-circuiting
Hint 3
Walk field paths segment by segment, checking that each intermediate value is a dictionary
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution separates two concerns: resolving field paths within the document, and recursively evaluating the expression tree.
Field Resolution: Split the field path on dots and traverse the document one level at a time. At each step, verify the current value is a dictionary and the next key exists. If either check fails, the field is missing. Use a sentinel object (not None) to represent missing fields, since documents can legitimately contain None values.
Tree Evaluation: Recursively process nodes:
- For
$and, useall()over child results — automatically returnsTruefor empty lists and short-circuits on the firstFalse - For
$or, useany()over child results — automatically returnsFalsefor empty lists and short-circuits on the firstTrue - For
$not, invert the child result - For comparison nodes, resolve the field then apply the operator. When the field is missing, return
Trueonly for$ne, otherwiseFalse
The recursive structure mirrors the tree structure, keeping the code clean and maintainable.
Why It Works: Each logical operator correctly implements its semantics through Python's built-in functions. Comparison nodes handle the missing-field special case before applying operators, preventing type errors. The sentinel ensures missing fields are never confused with explicit None values in the document.
Complexity:
- Time: O(N + L) where N is the number of nodes in the expression tree and L is the total length of all field paths. Each node is visited once, and short-circuiting may skip some subtrees. The
$inoperator adds O(k) where k is the length of the target list. - Space: O(D) for recursion stack where D is tree depth (at most 100). Field path splitting uses O(path_length) temporary space.
def match_filter(predicate, document):
missing = object()
def resolve_field(field_path):
current = document
for segment in field_path.split('.'):
if not isinstance(current, dict) or segment not in current:
return missing
current = current[segment]
return current
def evaluate_node(node):
if "$and" in node:
return all(evaluate_node(child) for child in node["$and"])
if "$or" in node:
return any(evaluate_node(child) for child in node["$or"])
if "$not" in node:
return not evaluate_node(node["$not"])
field_value = resolve_field(node["field"])
operator = node["op"]
target = node["val"]
if field_value is missing:
return operator == "$ne"
if operator == "$eq":
return field_value == target
if operator == "$ne":
return field_value != target
if operator == "$gt":
return field_value > target
if operator == "$gte":
return field_value >= target
if operator == "$lt":
return field_value < target
if operator == "$lte":
return field_value <= target
if operator == "$in":
return field_value in target
return False
return evaluate_node(predicate)