KatInterview

Design a Custom CSV Parsing and Filtering Engine

Data Structure DesignModel answer
MediumModel answerData Structure Designparsingdesign-dsstrings

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

  1. 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 (int or float). All other field values must remain strings.
  2. 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 value evaluate 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 as float, and text as str).

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.