Design a Custom CSV Parsing and Filtering Engine
Data Structure DesignModel answerLast updated
Implement an in-memory CSV query processor with auto-type inference and polymorphic field filtering.
You are asked to implement an in-memory processing engine for CSV data. The input data is supplied as a raw string where records are delimited by newlines and fields within each record are separated by commas. The first record defines the header schema.
Create a QueryEngine class that fulfills two primary responsibilities:
- Ingestion & Type Detection: Parse the input CSV string and maintain an internal structured representation. Values that consist exclusively of digits (with at most one optional decimal point) must be converted into numerical values (
intorfloat). All other field values must remain strings. - Filtering: Expose a
filter(col_name, operator, value)method that outputs all rows matching the given criteria.
Interface
from typing import Any, List
class QueryEngine:
def __init__(self, csv_data: str):
pass
def filter(self, col_name: str, operator: str, value: str) -> List[List[Any]]:
pass
Constraints & Semantics
- Supported relational operators are
==,=,!=,>,<,>=, and<=. Note that=should act as an alias for==. - Comparison type semantics: If both the record's field value and the filter input
valueevaluate to numeric types, perform a numeric comparison. If either side is non-numeric, perform a standard string (lexicographical) comparison using their raw textual forms. - Column headers are guaranteed to be unique.
- The returned rows should match the types assigned during initial ingestion (integers as
int, decimals asfloat, and text asstr).
Example
data = "name,age\nAlice,25\nBob,30"
engine = QueryEngine(data)
# Both sides numeric -> numeric comparison (25 > 20)
engine.filter("age", ">", "20")
# Returns: [['Alice', 25], ['Bob', 30]]
# Lexicographical comparison
engine.filter("name", "==", "Alice")
# Returns: [['Alice', 25]]
Hints
Hint 1
Differentiate strictly between integers and floating-point values so that whole numbers retain integer representations in the output.
Hint 2
Consider retaining both the raw string representation and the parsed numeric representation of each record to make lexicographical fallback efficient.
Hint 3
Using Python's operator module combined with a dispatch map can eliminate repetitive conditional logic when evaluating comparison operations.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
Building an in-memory query engine requires balancing clear structural separation between string parsing, type inferencing, and dynamic comparison dispatch.
1. Ingestion and Type Inference
During initialization (__init__), split the CSV payload by newlines and handle potential line-ending variances (like \r\n). Extract the first row as column headers and build an explicit map from header name to its positional index (col_name -> index).
To determine whether a value is numeric according to the strict rule (digits with an optional single decimal point), use a regular expression like ^\d+(\.\d+)?$.
- Avoid relying solely on
try ... except float(...)because standard string-to-float conversions accept values such as"infinity","NaN","1e5", or strings with leading/trailing spaces, which violate strict CSV text rules and can misclassify textual fields. - If a string matches the integer format (only digits), convert it to
int. If it contains a decimal point, convert it tofloat. Otherwise, keep it asstr.
2. Dual Representation for Fallback Operations
Because mixed-type comparisons (e.g., matching a numeric column value against a string filter input) must fallback to lexicographical string comparison, store two versions of every cell:
- The raw string representation parsed straight from the CSV.
- The typed value (
int,float, orstr).
When evaluating a filter:
- If both the target query parameter and the record's cell evaluate to numeric values, compare their typed representations.
- If either component is non-numeric, compare their raw string representations.
3. Operator Dispatching
Map incoming string operators ("==", "=", "!=", ">", "<", ">=", "<=") to functions from Python's standard operator module (operator.eq, operator.gt, etc.). This avoids long if/elif chains and allows $O(1)$ operator resolution.
Python 3 Implementation
import operator as op
import re
from typing import Any, List, Union
# Matches positive integers and positive decimals
NUMERIC_PATTERN = re.compile(r"^\d+(\.\d+)?$")
# Operator lookup table
OPERATORS = {
"==": op.eq,
"=": op.eq,
"!=": op.ne,
">": op.gt,
"<": op.lt,
">=": op.ge,
"<=": op.le,
}
def parse_cell(text: str) -> Union[int, float, str]:
"""Infers numeric type (int/float) if valid, otherwise returns original string."""
if NUMERIC_PATTERN.match(text):
return float(text) if "." in text else int(text)
return text
def is_numeric(val: Any) -> bool:
"""Checks if a parsed value is numeric (int or float)."""
return isinstance(val, (int, float)) and not isinstance(val, bool)
class QueryEngine:
def __init__(self, csv_data: str):
lines = [line.strip("\r") for line in csv_data.split("\n") if line.strip("\r").strip()]
if not lines:
self.headers: List[str] = []
self.header_to_idx = {}
self.raw_data: List[List[str]] = []
self.parsed_data: List[List[Any]] = []
return
self.headers = lines[0].split(",")
self.header_to_idx = {header: idx for idx, header in enumerate(self.headers)}
num_cols = len(self.headers)
self.raw_data = []
self.parsed_data = []
for line in lines[1:]:
raw_cells = line.split(",")
# Pad or truncate cells if the row length differs from header count
if len(raw_cells) < num_cols:
raw_cells.extend([""] * (num_cols - len(raw_cells)))
elif len(raw_cells) > num_cols:
raw_cells = raw_cells[:num_cols]
parsed_cells = [parse_cell(cell) for cell in raw_cells]
self.raw_data.append(raw_cells)
self.parsed_data.append(parsed_cells)
def filter(self, col_name: str, operator: str, value: str) -> List[List[Any]]:
if col_name not in self.header_to_idx:
raise KeyError(f"Column '{col_name}' does not exist in schema.")
if operator not in OPERATORS:
raise ValueError(f"Unsupported operator '{operator}'.")
col_idx = self.header_to_idx[col_name]
op_func = OPERATORS[operator]
parsed_target = parse_cell(value)
target_is_num = is_numeric(parsed_target)
matching_rows = []
for raw_row, parsed_row in zip(self.raw_data, self.parsed_data):
parsed_cell = parsed_row[col_idx]
raw_cell = raw_row[col_idx]
# Determine comparison mode
if target_is_num and is_numeric(parsed_cell):
is_match = op_func(parsed_cell, parsed_target)
else:
is_match = op_func(raw_cell, value)
if is_match:
# Return a deep copy of the typed row to prevent external mutation
matching_rows.append(list(parsed_row))
return matching_rows
Complexity Analysis
-
Time Complexity:
- Ingestion (
__init__): $\mathcal{O}(N \times C)$, where $N$ is the number of data rows and $C$ is the number of columns. Each field is split and parsed once via regex matching and conversion. - Querying (
filter): $\mathcal{O}(N \times C)$ in the worst-case for constructing the matching output records ($\mathcal{O}(N)$ comparisons and $\mathcal{O}(K \times C)$ space copying for $K$ matching rows). Column lookup is $\mathcal{O}(1)$.
- Ingestion (
-
Space Complexity:
- $\mathcal{O}(N \times C)$ memory storage to keep both typed and un-typed raw tabular structures in memory.