Implement a Robust CSV Parser
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-05-02
Problem Statement
Design and implement a CSV (Comma-Separated Values) parser in an object-oriented way. The parser should handle real-world complexities such as quoted fields, escaped characters, variable delimiters, and malformed inputs. The solution must be scalable, configurable, and robust.
✅ Functional Requirements
1.<span></span>Basic Parsing
2.<span></span>Parse a CSV file/string into rows and columns.
3.<span></span>Support default delimiter comma (,).
4.<span></span>Configurable Options
5.<span></span>Allow custom delimiters (e.g., ;, |, \t).
6.<span></span>Allow configuration for trimming whitespace.
7.<span></span>Quoted Fields
8.<span></span>Support fields enclosed in quotes (" ").
9.<span></span>Handle embedded delimiters inside quotes.
10.<span></span>Example: "New York, USA" should be treated as one field.
11.<span></span>Support escaped quotes ("" → ").
12.<span></span>Error Handling
13.<span></span>Gracefully handle malformed rows (different number of columns).
14.<span></span>Provide configurable strategies:
15.<span></span>Strict mode → throw exception.
16.<span></span>Lenient mode → skip/ignore malformed rows.
17.<span></span>Output Representation
18.<span></span>Provide rows as:
19.<span></span>List of strings per row.
20.<span></span>Optional: support mapping rows to key-value pairs using header row.
21.<span></span>Streaming Mode (Optional)
22.<span></span>Ability to read CSV line-by-line (useful for very large files).
⚙️ Non-Functional Requirements
1.<span></span>Follow OOP principles (encapsulation, modularity).
2.<span></span>Ensure efficiency (should handle large files with millions of rows).
3.<span></span>Code should be extensible for future support (e.g., TSV, JSON export).
🔐 Constraints
1.<span></span>Input file size: up to 1 GB.
2.<span></span>Encoding: assume UTF-8.
3.<span></span>Must handle both \n and \r\n line endings.
🧱 Key Classes to Model
1.<span></span>CSVParser – Core parsing logic.
2.<span></span>CSVConfig – Holds configuration (delimiter, error handling strategy, trim, etc.).
3.<span></span>CSVRow – Represents a parsed row (list of fields, or map if headers).
4.<span></span>CSVReader – Handles input stream/line reading.
5.<span></span>CSVException – Custom exception for malformed input.
🧪 Example Flow
<div><div><br /></div><div>Input CSV:</div><div>"name","age","city"</div><div>"John Doe",29,"New York, USA"</div><div>"Jane ""JJ"" Smith",34,"Los Angeles"</div><div><br /></div><div>Parsed Output:</div><div>Row 1: ["name", "age", "city"]</div><div>Row 2: ["John Doe", "29", "New York, USA"]</div><div>Row 3: ["Jane \"JJ\" Smith", "34", "Los Angeles"]</div></div>👉 This LLD problem tests a candidate’s ability to:
1.<span></span>Apply design patterns (Builder for config, Iterator for streaming rows).
2.<span></span>Handle edge cases in parsing logic.
3.<span></span>Write clean, extensible class design.