Middle · Explain · Parsing

Why does the quoted-field parser need a distinct after-quote state, and how do its length and field limits differ?

Think through your answer before opening the explanation.

Coding interviews

Reveal answer and reasoning

Parse one bounded comma-separated record with quoted fields and doubled quotes inside a quoted field. A quote may open only at the beginning of a field; after its closing quote only a delimiter or end is accepted. Preserve empty fields, including a trailing one. This defined classroom grammar is not a claim to implement every CSV dialect, multiline document or streaming encoding rule.

A state name should describe which next characters are legal, not just whether a quote was seen somewhere earlier. Unquoted, quoted and after-quote states make that grammar visible. End-of-input is also a transition: it finalizes unquoted or closed fields but rejects a field still inside quotes.

Each input code unit is inspected a bounded number of times, giving O(n) time and O(n) output/buffer storage within the accepted input limit. The maxFields check bounds the number of fields. StringBuilder and final strings still allocate; this is not a zero-allocation parser. The length limit is measured in UTF-16 code units because the input is already a string. A byte limit would belong before decoding or require a separate encoded-size calculation.

Bounding one record does not automatically bound a whole file containing many records, and StringBuilder capacity is not an allocation-free guarantee.

What a strong answer covers

  • Parse one bounded comma-separated record with quoted fields and doubled quotes inside a quoted field.
  • End materializes the current field, clears its builder and enforces the field-count limit.
  • Each input code unit is inspected a bounded number of times, giving O(n) time and O(n) output/buffer storage within the accepted input limit.

Common pitfall

Splitting on commas first destroys the information needed to recognize quoted delimiters. Accepting arbitrary characters after a closing quote creates ambiguous recovery behavior. Limits must apply before unbounded accumulation, and the parser should not return a partially accepted record after a grammar error.

Follow-up questions

  1. Test an empty record, an empty quoted field, an embedded quote in an unquoted field and characters after a closing quote. Hint: specify the expected field count for an empty input before deciding whether it is an error.
  2. Which state must survive a chunk boundary immediately after the first quote of a doubled quote?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions