KatInterview

Schema-Free Record Store with Column Indexing

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designhash-tablesindexingdata-structures

Last 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:

  1. 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).

  2. 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.

  3. 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