KatInterview

Build a CSV Parser from Scratch with Corruption Handling

StringsModel answer
MediumModel answerStringsparsingcsvstring-manipulation

Last updated

Write a from-scratch CSV tokenizer and data structure for downstream consumers, then extend it to handle rows with missing or extra fields.

You're building a data pipeline component. Your team receives telemetry data as a raw CSV string and needs to parse it into a structure that other engineering teams can query and consume. You cannot use a CSV library or dataframe loader—the tokenizer and data structure must be written from scratch.

You'll be given a sample input like this:

vehicle_id,timestamp,speed_mps,note
av-17,2024-03-01T10:00:00Z,12.5,"stopped, then resumed"
av-22,2024-03-01T10:00:01Z,8.0,

Part 1: Core Parser

Write a parser that processes the raw string and exposes a clean interface for downstream teams. Design both the parsing logic and the API consumers will use to access rows and fields.

Before coding, clarify:

  • Can fields contain quoted delimiters and line breaks?
  • Should you infer types, or return everything as strings?
  • How will consumers access the data—by row iteration, column extraction, or lookup?
  • What's the expected payload size?

Your solution should handle:

  • Quoted fields that may contain commas, newlines, or escaped quotes ("")
  • Empty fields versus missing fields
  • Trailing newlines and different line-ending styles (LF, CRLF)
  • The header row

Part 2: Corruption Recovery

Real-world payloads sometimes contain corrupted rows. The header is always correct, but data rows may have too few or too many fields, or an unterminated quote.

Extend your parser so corrupted rows don't crash the parse or silently misalign data into the wrong columns. Decide on a policy: should bad rows be dropped, preserved with gaps marked, or cause the entire parse to fail? Consumers need to know which rows failed and why.

Handle:

  • Rows with fewer fields than the header declares
  • Rows with more fields than expected
  • Diagnostic information: line number and failure reason
  • Isolation: one bad row shouldn't corrupt adjacent rows

Hints

Hint 1

State-machine tokenizing lets you track whether you're inside or outside quotes, handling escaped quotes and embedded delimiters correctly.

Hint 2

Consider returning a structure with methods like get_row(i), get_column(name), and iter_rows() so consumers can access data the way they need without coupling to your internal representation.

Hint 3

For corruption handling, validate row width immediately after tokenizing each line, and decide whether to collect errors in a list, raise on first failure, or skip bad rows with logging.