Build a CSV Query Engine
MicrosoftSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to parse structured text, perform basic type inference, and implement a filtering mechanism for tabular data.
Problem Statement
You are tasked with building a lightweight in-memory CSV query engine. The CSV file is provided as a string where rows are separated by newlines and columns are separated by commas. The first row contains headers.
Your task is to implement a QueryEngine class that performs the following:
- Parsing & Inference: Convert the CSV string into an internal representation. Values that consist entirely of digits (optionally with a decimal point) should be treated as numbers; otherwise, keep them as strings.
- Filter Method: Implement a
filter(column_name, operator, value)method that returns a list of rows matching the condition.
Function Signature
class QueryEngine:
def __init__(self, csv_data: str):
# Parses the CSV and stores it internally
pass
def filter(self, col_name: str, operator: str, value: str) -> List[List[Any]]:
# Filters rows based on the condition
pass
Constraints
- Operators include:
==,!=,>,=,<=. - If the column value and the input
valueare both numeric, perform numeric comparison. Otherwise, perform lexicographical comparison. - Headers are unique.
Example
data = "name,age\nAlice,25\nBob,30"
engine = QueryEngine(data)
# Numeric comparison (25 > 20)
engine.filter("age", ">", "20")
# Returns [['Alice', 25], ['Bob', 30]]
# String comparison
engine.filter("name", "==", "Alice")
# Returns [['Alice', 25]]
Edge Cases
- Empty CSV input.
- Numeric values being compared as strings due to parsing errors.
- Columns that do not exist in the header.
Hints
Hint 1
Use Python's built-in string `split()` method to break the input into rows and individual cells.
Hint 2
Try to convert each value to a float or int using a helper function; if it fails, keep the value as a string.
Hint 3
For the filter logic, store a mapping of header names to their column index for O(1) lookups during queries.
Follow-up questions
- How would you optimize this if you had to perform thousands of queries on a very large CSV file?
- How would you handle CSV fields that contain commas within quoted strings (e.g., 'New York, NY')?
- If you needed to support multiple filter conditions (e.g., age > 20 AND name == 'Alice'), how would you refactor the filter method?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.