CSV Parser - Problem

Parse CSV (Comma-Separated Values) data while handling advanced formatting rules. Your parser must correctly handle:

  • Quoted fields - Text enclosed in double quotes
  • Commas within quotes - Commas inside quoted fields don't separate columns
  • Escaped quotes - Double quotes within quoted fields are escaped as ""
  • Newlines within fields - Line breaks inside quoted fields are preserved

Return a 2D array where each sub-array represents a row of parsed fields.

Input & Output

Example 1 — Basic Quoted Fields
$ Input: csvData = "Name,Age,City\nJohn,25,NYC\n"Alice,30",Boston"
Output: [["Name","Age","City"],["John","25","NYC"],["Alice,30","Boston"]]
💡 Note: First two rows are simple comma-separated values. Third row has a quoted field "Alice,30" where the comma is preserved within the quotes.
Example 2 — Escaped Quotes
$ Input: csvData = "Product,Description\n""Premium"",""High quality"""
Output: [["Product","Description"],["Premium","High quality"]]
💡 Note: The field contains escaped quotes ("") which become single quotes in the output. ""Premium"" becomes "Premium".
Example 3 — Newlines in Fields
$ Input: csvData = "Name,Bio\n"John","Software\nDeveloper""
Output: [["Name","Bio"],["John","Software\nDeveloper"]]
💡 Note: The quoted field preserves the newline character within it, so the bio field contains a line break.

Constraints

  • 1 ≤ csvData.length ≤ 104
  • csvData contains valid CSV format
  • Quoted fields properly closed
  • Escaped quotes use "" format

Visualization

Tap to expand
CSV Parser OverviewINPUTRaw CSV Data:Name,Age,CityJohn,25,NYC"Alice,30",Boston"Say ""Hi""",EndChallenges:Commas in quotesEscaped quotes ("")Mixed quoted/unquotedALGORITHMState Machine Parser:1Track quote state (in/out)2Process each character3Handle commas by state4Manage escaped quotesState Transitions:Outside QuotesInside Quotes""RESULTParsed 2D Array:[["Name", "Age", "City"],["John", "25", "NYC"],["Alice,30", "Boston"],["Say \"Hi\"", "End"]]Key Benefits:Commas preserved in quotesQuotes properly unescapedClean field separationKey Insight:Track your context state as you scan - each comma's meaning depends on whetheryou're inside or outside quotes, enabling single-pass parsing with O(n) efficiency.TutorialsPoint - CSV Parser | State Machine Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen