Design an In-Memory Database Engine
Data Structure DesignAuto-graded · 19 test casesLast 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:
-
["SET", row_key, col_key, value]: Assignsvalueto the columncol_keyof the record with keyrow_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. -
["GET", row_key, col_key]: Retrieves the stored value attable[row_key][col_key].- Returns the string value if the record and column both exist.
- Returns
"NULL"if therow_keyorcol_keyis not present.
-
["SELECT", where_col, where_value, order_by_col]: Finds all records (row_keys) where the columnwhere_colcontains exactlywhere_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_colcolumn, 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 theirrow_keystrings 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"".
- The matching record keys must be sorted in ascending order primarily by the value in column
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, andvaluestrings 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']
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to simulate an in-memory key-value database table that supports dynamic row and column creation, value point lookups, and selection queries with custom sorting and filtering.
We can model the database table using a nested dictionary structure:
table[row_key]points to a dictionary of column-value pairscol_key -> value.
-
SET: Access (or instantiate)table[row_key]and assignrow[col_key] = value. This takes $O(1)$ amortized time. -
GET: Check ifrow_keyexists intableand ifcol_keyexists within that row. If both exist, append the value to the result list; otherwise append"NULL". -
SELECT: Iterate through all rows intable. A row qualifies ifrow.get(where_col) == where_value. For each matching row, construct a sort tuple(sort_val, row_key), wheresort_val = row.get(order_by_col, ""). Since standard tuple sorting in Python compares elements position-by-position:- Primary ordering will be based on
sort_valin ascending lexicographical order (with missing columns defaulting to"", which sorts before any non-empty string). - Secondary ordering (tie-breaking) will automatically default to
row_keyascending. Finally, join the sorted matching keys with spaces and record the output string.
- Primary ordering will be based on
Complexity Analysis
- Time Complexity:
SET: $O(L)$ where $L$ is the string length.GET: $O(L)$ for hash lookup.SELECT: $O(N \cdot L + M \log M \cdot L)$, where $N$ is total number of active rows, and $M$ is the number of matching rows.
- Space Complexity: $O(R \cdot C \cdot L)$ auxiliary storage to retain $R$ rows with $C$ columns each, plus $O(U)$ space for the query result list.
Python Reference Solution
from typing import List
def in_memory_table(commands: List[List[str]]) -> List[str]:
table = {}
output = []
for command in commands:
op = command[0]
if op == "SET":
_, row_key, col_key, value = command
table.setdefault(row_key, {})[col_key] = value
elif op == "GET":
_, row_key, col_key = command
row = table.get(row_key)
if row is not None and col_key in row:
output.append(row[col_key])
else:
output.append("NULL")
elif op == "SELECT":
_, where_col, where_value, order_by_col = command
matches = []
for r_key, row in table.items():
if row.get(where_col) == where_value:
sort_val = row.get(order_by_col, "")
matches.append((sort_val, r_key))
matches.sort()
output.append(" ".join(r_key for _, r_key in matches))
return output