In-Memory Row Store with Filter, Sort, and Projection
Data Structure DesignAuto-graded · 3 test casesLast updated
Tests ability to build a stateful table abstraction that processes insert and query operations with filtering, sorting, and column projection.
Problem
You are building a lightweight in-memory row store. Given a fixed list of column names at construction time, your store must handle two types of operations applied in sequence: inserting rows and querying them.
Implement the function run_table(columns, operations, arguments) that processes a series of operations on a single table and returns their results in order.
Parameters
columns: A list of strings naming the columns of the table, in schema order.operations: A list of strings, each either"insert"or"query".arguments: A list of argument lists, one per operation (same length and order asoperations).
Operation Specs
"insert"
arguments[i] is a one-element list containing a dict that maps column names to values. Store the row. Values for columns not present in the dict should be recorded as None. Return None for this operation.
"query"
arguments[i] is a three-element list [select, where, order_by]:
select: A list of column names to include in each returned row. IfNone, include all columns in schema order.where: A dict of equality conditions — only rows where every specified column matches the given value are included. IfNone, all rows pass. A condition on a column that does not exist in the schema matches no rows (return[]).order_by: A two-element list[column_name, direction]wheredirectionis"asc"or"desc". IfNone, rows are returned in insertion order.
Return the list of matching row dicts (projected to the selected columns).
Sorting Rules
- When two rows have equal values in the sort column, their relative insertion order is preserved (stable sort).
Nonevalues sort before all non-Nonevalues in"asc"order and after all non-Nonevalues in"desc"order.- When a column contains a mix of integers and strings, integers sort before strings.
Return Value
Return a list with one entry per operation:
Nonefor each"insert".- A list of dicts for each
"query".
Constraints
1 ≤ len(columns) ≤ 50- All column names are non-empty strings.
1 ≤ len(operations) ≤ 1000- Row values are integers, strings, or
None. selectcolumns,wherekeys, andorder_bycolumns are drawn from the schema (except where edge-case rules above apply).- At most 500
"insert"operations and at most 500"query"operations.
Examples
Example 1
Input: run_table(['name', 'age', 'city'], ['insert', 'insert', 'insert', 'query'], [[{'name': 'Alice', 'age': 30, 'city': 'NY'}], [{'name': 'Bob', 'age': 25, 'city': 'LA'}], [{'name': 'Charlie', 'age': 30, 'city': 'SF'}], [['name'], {'age': 30}, ['name', 'desc']]])
Output: [None, None, None, [{'name': 'Charlie'}, {'name': 'Alice'}]]
Hints
Hint 1
Process each operation in sequence and accumulate results. For inserts, normalize the incoming dict so every schema column is always present (using None for missing ones). This keeps query logic uniform.
Hint 2
For the where filter, iterate over all stored rows and check every condition in the where dict. If the where dict references a column not in the schema, no row can ever match, so return [] immediately.
Hint 3
Sort after filtering but project (select) after sorting. That way you can sort by a column that isn't in the select list. Use a stable sort with a composite key that encodes type first (None, int, str), then value, then flip direction with reverse=True.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function simulates three classic relational database phases — filter, sort, project — applied in that order for every query. Doing them in this sequence matters: sorting before projecting means you can sort by a column that isn't in the select list, which mirrors standard SQL behavior.
Insert
On each insert, normalize the incoming dict by building a new dict that covers every schema column, defaulting to None for anything missing. This means downstream query code can always do row[col] without guarding against KeyError.
Query
Filter (WHERE). Walk every stored row. For each condition in the where dict, check whether the column exists in the schema and whether the row's value matches. If the column is not in the schema at all, no stored row can satisfy it, so the any(...) guard immediately skips the row — meaning the result will be []. If where is None, all rows pass.
Sort (ORDER BY). Use cmp_to_key with a custom comparator rather than a plain key= lambda, because the mixed-type case (int vs str) needs explicit handling that a simple tuple key can't express cleanly. The comparator encodes:
- Both
None: equal. - One
None: inasc,Nonecomes first (return-1); indesc,Nonecomes last (return+1). - Same type: natural
</>. - Mixed types: use the type name string as a proxy (
"int" < "str"lexicographically), so integers always sort before strings. - Flip the sign for
desc.
Python's list.sort is stable, so rows with identical sort keys retain their relative insertion order.
Project (SELECT). Build the final list of dicts, keeping only the requested columns. This step happens last so sorting by a non-selected column still works correctly.
Why it's correct
- Normalization on insert ensures the schema view of every row is complete and consistent.
- The
whereshort-circuit on unknown columns matches the specified edge-case rule without raising an exception. cmp_to_keywith explicitNoneand mixed-type handling avoidsTypeErrorin Python 3 comparisons.- Projecting after sorting means column presence in
selecthas no effect on sort correctness.
Complexity
| Phase | Time | Notes |
|---|---|---|
| Insert | O(C) per row | C = number of schema columns |
| Filter | O(n · |where|) | n = rows stored so far |
| Sort | O(m log m) | m = rows after filtering |
| Project | O(m · s) | s = columns in select |
| Space | O(n · C) | One normalized dict per row |
For the given constraints (≤ 500 inserts, ≤ 500 queries, ≤ 50 columns) this is well within typical time limits.
Reference Solution
from functools import cmp_to_key
from typing import List
def run_table(columns: List[str], operations: List[str], arguments: List[List]) -> List:
column_set = set(columns)
rows = []
def compare_values(left, right, direction):
# None handling: asc -> None first, desc -> None last
if left is None and right is None:
return 0
if left is None:
return -1 if direction == 'asc' else 1
if right is None:
return 1 if direction == 'asc' else -1
# Same type: compare directly
if type(left) is type(right):
if left < right:
result = -1
elif left > right:
result = 1
else:
result = 0
else:
# Mixed types: use type name as tiebreaker (int < str lexicographically)
left_key = (type(left).__name__, str(left))
right_key = (type(right).__name__, str(right))
result = (left_key > right_key) - (left_key < right_key)
return result if direction == 'asc' else -result
result = []
for operation, args in zip(operations, arguments):
if operation == 'insert':
input_row = args[0]
# Normalize: every schema column present, missing -> None
rows.append({col: input_row.get(col) for col in columns})
result.append(None)
elif operation == 'query':
select, where, order_by = args
# --- Filter ---
filtered = []
for row in rows:
if where is not None and any(
col not in column_set or row.get(col) != val
for col, val in where.items()
):
continue
filtered.append(row)
# --- Sort ---
if order_by is not None:
sort_col, direction = order_by
filtered.sort(key=cmp_to_key(
lambda a, b: compare_values(
a.get(sort_col), b.get(sort_col), direction
)
))
# --- Project ---
out_cols = columns if select is None else select
result.append([
{col: row.get(col) for col in out_cols}
for row in filtered
])
return result