KatInterview

Design an In-Memory Database Engine

Data Structure DesignAuto-graded · 19 test cases
MediumAuto-gradedData Structure Designhash-mapdesignsorting

Last updated

Simulate an in-memory single-table key-value store supporting lookup, update, and sorted conditional selection queries.

Design an in-memory single-table relational storage system that handles text-based records and processes a list of operational instructions.

Each entry (row) is identified by a unique string ID row_key. Within each row, values are associated with column name strings (col_key). All record values are strings.

You are given a list of instructions, where each instruction is represented as a list of strings:

  1. ["SET", row_key, col_key, value]: Assigns value to the column col_key of the record with key row_key. If the record or column does not exist, it is created. If it already exists, its value is overwritten. This operation produces no output line.

  2. ["GET", row_key, col_key]: Retrieves the stored value at table[row_key][col_key].

    • Returns the string value if the record and column both exist.
    • Returns "NULL" if the row_key or col_key is not present.
  3. ["SELECT", where_col, where_value, order_by_col]: Finds all records (row_keys) where the column where_col contains exactly where_value.

    • The matching record keys must be sorted in ascending order primarily by the value in column order_by_col.
    • If a matching record does not contain the order_by_col column, treat its sort key for that column as an empty string "".
    • If two matching records have identical values for order_by_col (including when both are missing it), break ties by comparing their row_key strings in ascending lexicographical order.
    • Returns a single string containing all matching row_keys separated by a single space (e.g., "r1 r2 r3"). If no records match, returns an empty string "".

Output Format

The function should process the sequence of instructions in order and return a list of string responses corresponding to all GET and SELECT queries.

Constraints

  • $1 \le \text{len(commands)} \le 2 \times 10^5$
  • All row_key, col_key, where_col, order_by_col, and value strings consist of alphanumeric characters and have length $\le 50$.
  • Comparison and sorting are strictly lexicographical (e.g., "10" < "9").

Examples

Example 1

Input: in_memory_table([['SET', 'r1', 'name', 'Ada'], ['SET', 'r1', 'city', 'London'], ['SET', 'r2', 'name', 'Grace'], ['SET', 'r2', 'city', 'New York'], ['GET', 'r1', 'name'], ['GET', 'r3', 'name'], ['SELECT', 'name', 'Ada', 'city']])

Output: ['Ada', 'NULL', 'r1']