Mini Query Engine: Filter, Sort, and Project Rows
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests ability to implement a pipeline of filter, multi-column sort, and column projection over a list of in-memory row dicts.
Mini Query Engine: Filter, Sort, and Project Rows
You are given a table represented as a list of rows, where each row is a dictionary mapping column names to values. Implement a function that processes the table through three stages in order:
- Filter — keep only the rows that satisfy every condition in a given list.
- Sort — reorder the surviving rows by one or more columns, in either ascending or descending direction.
- Project — return only the requested columns from each surviving row.
Stage details
Filtering
Each condition is a three-element list [column, operator, value]. A row passes only when all conditions hold (AND semantics). Supported operators are =, !=, <, <=, >, >=. If a row is missing the column named in a condition, the row does not pass. An unrecognised operator must raise ValueError.
Sorting
order_by is a two-element list [sort_columns, ascending], where:
sort_columnsis a list of column names defining the sort priority (first element = primary key, and so on).ascendingis a single boolean:Truemeans smallest first,Falsemeans largest first, applied uniformly to every sort column.
Use a sequence of stable sorts moving from the least-significant key to the most-significant key. This produces correct lexicographic ordering across all sort columns while preserving the original row order for ties.
Projection
Build the output by keeping only the keys listed in columns, and only when the key is actually present in a surviving row. Omit keys that are absent from a particular row rather than inserting None.
Constraints
0 <= len(rows) <= 10^41 <= len(columns) <= 200 <= len(conditions) <= 10sort_columnscontains between 1 and 5 column names;ascendingis a singlebool- Row values are comparable scalars (strings, numbers). ISO-format date strings such as
"1906-12-09"sort correctly as plain strings. - Column names are non-empty strings.
- All rows in
rowsshare the same set of keys (no sparse schema). order_byalways contains exactly two elements;conditionsmay be an empty list.
Examples
Example 1
Input: run_query([{'id': '1', 'name': 'Ada', 'birthday': '1815-12-10'}, {'id': '2', 'name': 'Charles', 'birthday': '1791-12-26'}, {'id': '3', 'name': 'Grace', 'birthday': '1906-12-09'}], ['id'], [['name', '=', 'Charles']], [['birthday'], False])
Output: [{'id': '2'}]
Example 2
Input: run_query([{'id': '1', 'name': 'Ada', 'birthday': '1815-12-10'}, {'id': '2', 'name': 'Charles', 'birthday': '1791-12-26'}, {'id': '3', 'name': 'Grace', 'birthday': '1906-12-09'}], ['id', 'name'], [], [['birthday'], False])
Output: [{'id': '3', 'name': 'Grace'}, {'id': '1', 'name': 'Ada'}, {'id': '2', 'name': 'Charles'}]
Hints
Hint 1
Work through the pipeline in order: filter first, then sort, then project. Projecting before sorting is a common mistake — you may discard a column that you still need as a sort key.
Hint 2
For multi-column sorting, apply a stable sort once per key, moving from the least significant key to the most significant. Python's built-in sort is stable, so earlier passes are preserved when later passes encounter ties.
Hint 3
Build a lookup table mapping operator strings like '=' and '>=' to their corresponding Python functions (operator.eq, operator.gt, etc.) so each condition can be evaluated with a single dictionary lookup rather than a chain of if-statements.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function is a three-stage pipeline. Each stage is independent, which makes it easy to reason about correctness and test in isolation.
Stage 1: Filter
Build an operator lookup table mapping each symbol string to a Python comparison function. For each row, walk through every condition. If the column is absent from the row, or the comparison returns False, the row is rejected immediately. Only rows where every condition passes are kept. This is O(n · c) where n is the number of rows and c the number of conditions.
Stage 2: Sort
Multi-column, single-direction sorting is handled by running Python's built-in list.sort once per sort key, iterating from the last (least-significant) key to the first (most-significant). Because list.sort is stable, rows that compare equal on the primary key retain the relative order established by the secondary-key pass. This chains correctly across any number of keys and produces lexicographic ordering. Ascending/descending is controlled by reverse=not ascending.
This step costs O(s · m log m), where s is the number of sort columns and m the number of rows that survived filtering.
Stage 3: Project
Iterate over the surviving rows and build a new dict containing only the requested column names that are actually present in each row. This avoids KeyError on sparse rows and costs O(m · p) where p is the number of projected columns.
Why the pipeline order matters
Sorting must happen before projection. If you projected first you could drop a column that is named in sort_columns, making the subsequent sort meaningless or incorrect (ORDER BY birthday after projecting only id would have nothing to sort on).
Complexity
| Stage | Time | Space |
|---|---|---|
| Filter | O(n · c) | O(m) |
| Sort | O(s · m log m) | O(1) extra |
| Project | O(m · p) | O(m · p) |
Edge cases
conditionsis empty: the filter loop is a no-op and all rows pass through.sort_columnshas one entry: the reversed loop runs once, behaving like a plain single-key sort.- A column listed in
columnsis absent from a particular row: the dict comprehension silently skips it rather than insertingNone. - An unrecognised operator raises
ValueErrorbefore any row is evaluated.
Reference solution
from typing import Dict, List
def run_query(rows: List[Dict], columns: List[str], conditions: List[List], order_by: List) -> List[Dict]:
operators = {
"=": lambda a, b: a == b,
"!=": lambda a, b: a != b,
"<": lambda a, b: a < b,
"<=": lambda a, b: a <= b,
">": lambda a, b: a > b,
">=": lambda a, b: a >= b,
}
# Stage 1: Filter — keep rows satisfying every condition.
filtered = []
for row in rows:
matches = True
for column, op, value in conditions:
if op not in operators:
raise ValueError(f"Unsupported operator: {op}")
if column not in row or not operators[op](row[column], value):
matches = False
break
if matches:
filtered.append(row)
# Stage 2: Sort — stable passes from least- to most-significant key.
sort_columns, ascending = order_by
for column in reversed(sort_columns):
filtered.sort(key=lambda row: row.get(column), reverse=not ascending)
# Stage 3: Project — emit only requested columns present in each row.
return [{column: row[column] for column in columns if column in row} for row in filtered]