Schema-Free Record Store with Column Indexing
Data Structure DesignAuto-graded · 16 test casesLast updated
Tests ability to design an in-memory key-value store with flexible schemas, column-based retrieval, and multi-field filtering logic.
Build an in-memory record store that supports flexible, schema-free documents.
Each record is a dictionary mapping field names (strings) to values (any type). Records need not share the same fields—one record may contain fields that others lack entirely.
Your implementation must support three operations, provided as a sequence of commands:
-
insert: Add a new record to the store. Returns a unique integer identifier assigned to that record (starting from 0 and incrementing by 1 for each insert).
-
query: Given a field name, return all records that contain that field. Each result is a
[record_id, value]pair. Results must appear in insertion order. -
filter: Given a dictionary of field-value pairs, return the IDs of all records that contain all the specified fields with exactly the specified values. A record matches only if it has every field mentioned in the filter and each field's value equals the corresponding filter value. Records lacking any of the filter fields do not match. Return IDs in insertion order.
Implement a function that processes a batch of operations and returns the results of each operation in order.
Constraints:
- 1 ≤ number of operations ≤ 1000
- Field names are non-empty strings
- Values can be integers, strings, booleans, or null
- Each record contains 0 to 20 fields
- Filter conditions contain 1 to 10 field-value pairs
- All record IDs are non-negative integers assigned sequentially
Examples
Example 1
Input: schema_free_store(['insert', 'insert', 'insert', 'query', 'filter', 'filter'], [[{'name': 'Ada', 'age': 36}], [{'name': 'Lin', 'city': 'Oslo'}], [{'name': 'Sam', 'age': 36, 'city': 'Oslo'}], ['age'], [{'age': 36}], [{'city': 'Oslo', 'age': 36}]])
Output: [0, 1, 2, [[0, 36], [2, 36]], [0, 2], [2]]
Example 2
Input: schema_free_store(['insert', 'insert', 'query', 'filter'], [[{'name': 'A', 'active': True}], [{'name': 'B', 'active': False}], ['active'], [{'active': False}]])
Output: [0, 1, [[0, True], [1, False]], [1]]
Hints
Hint 1
Maintain an inverted index: for each field name, track which records contain it along with their values
Hint 2
When filtering, start with records that have one of the required fields, then check all conditions rather than scanning every record
Hint 3
Preserve insertion order by using the record ID sequence; dict iteration order in Python 3.7+ maintains insertion order automatically
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is efficiently retrieving records by field name without scanning every record each time. The solution maintains all records in a list indexed by their insertion order, which doubles as the record ID.
For insert, we append the record dictionary to the list and return its index.
For query, we scan through all records checking which ones contain the requested field. Since we store records in insertion order and Python dicts maintain iteration order (3.7+), we naturally return results in the correct sequence.
For filter, we check each record to see if it contains all required fields with matching values. A record matches only when every field specified in the filter exists in the record and holds the exact value given. Records missing any filter field are excluded.
The implementation uses a straightforward linear scan. While this is not the most efficient approach for large datasets, it correctly handles all edge cases: records with missing fields, empty records, and filters that reference fields not present in some records.
Why This Works
- Correctness: Each operation is independent. Insert assigns sequential IDs. Query and filter iterate the full record list, so they never miss a record.
- Missing field handling: The condition
field in record and record[field] == valueensures that records lacking a field always fail that condition, which matches the expected behavior. - Order preservation: Using list index as record ID and iterating with
enumerateguarantees insertion order.
Complexity
Let n be the number of records, k the average number of fields per record, and f the number of conditions in a filter.
- insert: O(k) to copy the record dictionary
- query: O(n · k) worst case to check all records
- filter: O(n · f · k) to check all records against all conditions
Space: O(n · k) to store all records.
Optimization path: An inverted index mapping each field name to the set of record IDs containing it would reduce query to O(result size) and filter to O(smallest field set · f). The tradeoff is O(n · k) extra space and more complex insert logic.
from typing import List
def schema_free_store(operations: List[str], arguments: List[List]) -> List:
records = []
results = []
for operation, args in zip(operations, arguments):
if operation == "insert":
records.append(dict(args[0]))
results.append(len(records) - 1)
elif operation == "query":
field = args[0]
results.append([
[record_id, record[field]]
for record_id, record in enumerate(records)
if field in record
])
elif operation == "filter":
conditions = args[0]
results.append([
record_id
for record_id, record in enumerate(records)
if all(field in record and record[field] == value
for field, value in conditions.items())
])
else:
raise ValueError("unknown operation")
return results