Build a Record Filter with Nested Query Conditions
Data Structure DesignAuto-graded · 20 test casesLast updated
Evaluate structured filter expressions with comparison, membership, and logical operators over in-memory records
Problem Statement
Build a system that stores dictionary records in memory and filters them using a structured query language. The language supports field comparisons, membership tests, and nested logical combinations.
Implement a function execute_record_operations that processes a sequence of operations on a record store:
"insert": Add a dictionary record to the store."query": Return all stored records matching a filter condition.
Filter Condition Format
A condition is represented as a dictionary and falls into one of two categories:
1. Field Comparison: { "field": { "operator": value } }
Available operators:
"$eq": Field equals the given value"$gt": Field is strictly greater than the value"$lt": Field is strictly less than the value"$in": Field value appears in the provided list"$nin": Field value does not appear in the provided list
2. Logical Combination:
{ "$and": [cond1, cond2, ...] }: All conditions must evaluate to true{ "$or": [cond1, cond2, ...] }: At least one condition must evaluate to true{ "$not": cond }: Negates the result of the condition
An empty condition {} matches all records.
Field Evaluation Rules
- Records are dictionaries with string keys and values that may be integers, floats, strings, or
None. - If a field referenced in a condition does not exist in a record, treat it as
None. - For
"$gt"and"$lt":- If the field value is
None, the comparison returnsFalse. - If the field value and comparison target have incompatible types (e.g., integer vs string), the comparison returns
False.
- If the field value is
- Records are returned in insertion order.
Function Signature
def execute_record_operations(operations: List[str], arguments: List[List[object]]) -> List[object]
operations[i]is either"insert"or"query"- For
"insert",arguments[i][0]is the record dictionary - For
"query",arguments[i][0]is the condition dictionary - Return a list where:
- Insert operations contribute
None - Query operations contribute a list of matching records
- Insert operations contribute
Constraints
- At most 10,000 insert operations
- At most 5,000 query operations
- Maximum nesting depth of logical operators is 10
- Field names contain only alphanumeric characters
- String values contain only alphanumeric characters
Examples
Example 1
Input: execute_record_operations(['insert', 'insert', 'insert', 'query'], [[{'id': 1, 'name': 'Alice', 'age': 30, 'status': 'ACTIVE'}], [{'id': 2, 'name': 'Bob', 'age': 24, 'status': 'PENDING'}], [{'id': 3, 'name': 'Charlie', 'age': 35, 'status': 'ACTIVE'}], [{'$and': [{'status': {'$eq': 'ACTIVE'}}, {'age': {'$gt': 25}}]}]])
Output: [None, None, None, [{'id': 1, 'name': 'Alice', 'age': 30, 'status': 'ACTIVE'}, {'id': 3, 'name': 'Charlie', 'age': 35, 'status': 'ACTIVE'}]]
Example 2
Input: execute_record_operations(['insert', 'insert', 'insert', 'query'], [[{'id': 1, 'name': 'Alice', 'age': 30, 'status': 'ACTIVE'}], [{'id': 2, 'name': 'Bob', 'age': 24, 'status': 'PENDING'}], [{'id': 3, 'name': 'Charlie', 'age': 35, 'status': 'ACTIVE'}], [{'$or': [{'status': {'$in': ['PENDING', 'ARCHIVED']}}, {'name': {'$eq': 'Charlie'}}]}]])
Output: [None, None, None, [{'id': 2, 'name': 'Bob', 'age': 24, 'status': 'PENDING'}, {'id': 3, 'name': 'Charlie', 'age': 35, 'status': 'ACTIVE'}]]
Hints
Hint 1
Model the condition as a tree where leaves are field tests and internal nodes are logical operators, then evaluate it recursively for each record
Hint 2
Handle missing fields by using dict.get() which returns None by default, matching the specified behavior
Hint 3
For comparison operators that might fail with incompatible types, wrap them in try-except to return False on TypeError
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The filter condition is a tree structure. Leaf nodes are field comparisons like {"age": {"$gt": 25}}. Internal nodes are logical operators ($and, $or, $not) that combine child conditions. To evaluate whether a record matches, we recursively walk this tree.
The core function evaluate_condition(record, condition) works as follows:
- Empty condition: Return
True(matches everything) - Logical operators: Extract the key (
$and,$or, or$not)- For
$and: ReturnTrueonly if all child conditions match (use Python'sall) - For
$or: ReturnTrueif any child condition matches (use Python'sany) - For
$not: Return the negation of the child condition
- For
- Field comparison: Extract the field name and operator
- Get the field value using
dict.get(), which returnsNonefor missing fields - Apply the operator (
$eq,$gt,$lt,$in,$nin) - For
$gtand$lt, guard againstNonevalues and type mismatches with try-except
- Get the field value using
Storage uses a simple list to maintain insertion order. Each query scans all records and keeps those where evaluate_condition returns True.
Why This Works
- Logical operators map to Python semantics:
all()implements AND,any()implements OR, and both short-circuit for efficiency - Missing fields are
None: Usingrecord.get(field)automatically handles missing keys per the specification - Type-safe comparisons: The try-except around
$gtand$ltcatchesTypeErrorwhen comparing incompatible types (like int vs string), returningFalseas required - Order preservation: List comprehension maintains insertion order
- Edge cases: Empty
$andreturnsTrue(all of nothing), empty$orreturnsFalse(any of nothing)
Complexity
Let N = number of stored records, Q = number of nodes in the condition tree, L = total length of membership lists.
- Time per insert: O(1) amortized
- Time per query: O(N × (Q + L)) — each record evaluates the full condition tree
- Space: O(N) for storage plus O(depth) for recursion stack (max depth 10)
With 10,000 records and 5,000 queries, total operations are manageable. Logical operators short-circuit when possible, reducing average-case work.
Implementation
from typing import List
def execute_record_operations(operations: List[str], arguments: List[List[object]]) -> List[object]:
stored_records = []
results = []
def evaluate_condition(record, condition):
if not condition:
return True
key = next(iter(condition))
value = condition[key]
if key == "$and":
return all(evaluate_condition(record, child) for child in value)
if key == "$or":
return any(evaluate_condition(record, child) for child in value)
if key == "$not":
return not evaluate_condition(record, value)
field_value = record.get(key)
operator, target = next(iter(value.items()))
if operator == "$eq":
return field_value == target
if operator == "$in":
return field_value in target
if operator == "$nin":
return field_value not in target
if operator == "$gt":
if field_value is None:
return False
try:
return field_value > target
except TypeError:
return False
if operator == "$lt":
if field_value is None:
return False
try:
return field_value < target
except TypeError:
return False
return False
for op, args in zip(operations, arguments):
if op == "insert":
stored_records.append(args[0])
results.append(None)
elif op == "query":
filter_condition = args[0]
results.append([rec for rec in stored_records if evaluate_condition(rec, filter_condition)])
return results