In this article
Before you start
This page belongs to the machine learning (ML) coding round guide, which covers the other coding tasks that appear next to this one.
Why interviewers ask this
A parsing task shows in a few minutes whether a candidate can be trusted with real data, which is rarely tidy. Candidates report tasks of this kind in coding loops at AI labs and large tech companies: ranking the best-selling products in a CSV string, cleaning a messy sales dataset, or computing statistics over parsed records. These are candidate reports; no public source defines the round as an official format, so treat the shape below as a pattern, not a rule.
A weak answer writes line.split(","), sums a column and stops. A strong answer asks what a missing value means, notices duplicates and inconsistent spelling, states how ties are broken, and says which standard deviation it computed. A Staff-level answer also tests its own parser on a nasty row before the interviewer does, and explains each cleaning decision as a trade-off.
The data-parsing round from first principles
- Data-parsing round
- The data-parsing round is a coding interview stage, reported by candidates, in which you turn raw text such as a CSV string into clean records and then compute counts, a top K or summary statistics, judged on edge cases and stated assumptions as much as on the final number.
- CSV
- CSV, short for comma-separated values, is a plain-text table format in which each line is one row and commas separate the fields, with double quotes around a field that itself contains a comma, a quote or a line break.
- Top K
- Top K is the K items with the largest value of some measure, such as the K products with the most units sold, so the question is only complete once you say which measure ranks the items and how ties are broken.
In plain words
Think of a pile of handwritten order slips. Before anyone can count anything you must read each slip correctly. Then you throw away photocopies of the same slip and fix spellings. Then you decide what to do with a slip whose quantity is smudged. Only after that do you tally. The analogy breaks in one place. Slips come with a printed layout. CSV has no single universal standard, so files from different programs differ in small ways, as the Python csv documentation warns.
In one precise sentence, the round is a four-stage pipeline: parse text into records, clean the records, aggregate them, and report the result with its assumptions. The steps below follow that order.
Step 1: Parse the text into rows without splitting on commas
Parsing means turning the text into a list of rows, each a list of fields. Do not use line.split(","). The Request for Comments (RFC) number 4180 says that fields containing line breaks, double quotes and commas should be enclosed in double quotes, and that a quote inside such a field is written as two quotes. A quoted field is a field wrapped in double quotes so that commas inside it are data, not separators.
A plain split cuts the quoted row 2,"Cable, braided",2 into four pieces instead of three. In the worked example, two of ten rows are garbled this way.1 In real code use the standard csv module, and open files with newline='', as its documentation instructs. Interviews often hand you a string, so know the idea: walk the characters, flip an "inside quotes" flag at each quote, and split only when the flag is off. The hand parser below handles one line at a time; to support line breaks inside quotes, walk the whole text and end a row only at a newline outside quotes.
def parse_line(line):
fields, cur, in_q, i = [], [], False, 0
while i < len(line):
ch = line[i]
if in_q:
if ch == '"':
if i + 1 < len(line) and line[i + 1] == '"':
cur.append('"'); i += 1 # doubled quote = one literal quote
else:
in_q = False
else:
cur.append(ch)
elif ch == '"':
in_q = True
elif ch == ',':
fields.append(''.join(cur)); cur = []
else:
cur.append(ch)
i += 1
fields.append(''.join(cur))
return fieldsStep 2: Clean duplicates, spellings and missing values
Cleaning means making equal things look equal and deciding what to do with gaps. Three jobs recur. First, remove exact duplicate rows, keyed on every field, so one order is not counted twice. Keying on every field is one choice; if the same order_id can appear with different values, ask which row wins. Second, normalise text: trim spaces and fold case, so widget and Widget become one product. Trimming is your cleaning decision, not a format rule, because RFC 4180 says spaces are part of a field. Third, handle missing values by an explicit rule, such as dropping the row or filling a value.
Each rule changes the answer, so say it aloud. In the worked example, ten parsed rows become nine after duplicate removal and eight after dropping the row with no quantity.1 Six distinct spellings of product names collapse to four.1 Count the rows that survive each step; an interviewer who sees those counts knows you did not lose data silently. Input here is raw rows; output is clean records.
Step 3: Aggregate with a counter and take the top K
Aggregation turns clean records into totals. Use a dictionary, or a Counter, keyed by product name and add the quantity for each record. For "top K most sold" first fix the measure: units (the sum of quantities) or orders (the number of rows). They can disagree, as the chart below shows. Then fix tie-breaking, for example alphabetically by name, so the output is the same every run.
To take the K largest, the heapq documentation says nlargest returns the n largest elements and is equivalent to sorting in descending order and slicing. By standard analysis, a heap of size K costs about n log k for n items, against n log n for a full sort; since you rank distinct products, n is usually small, so either is acceptable if you say so. Overall, parsing and aggregation are O(n) in the characters and rows, plus the top-K cost. Statistics come from the same clean list: the mean, the median and the standard deviation, a number that measures how far values typically sit from their mean.
Step 4: Report the result with its assumptions
Reporting means giving the answer and the decisions behind it in a few sentences. A number alone invites the question "how did you treat missing quantities?"; a number with its assumptions ends it. Say which measure ranked the products, how ties were broken, what was dropped and how many rows that was, and which standard deviation you computed. Report the answer together with the assumptions you made.
The two standard deviations differ in the divisor. The population version divides the summed squared distances by the count n; the sample version divides by n minus one, and is larger. Use the sample version when the rows are a sample of a bigger process, and the population version when the rows are everything. If the interviewer does not say, pick one and name it.
Step-by-step description
- Turn text into rows without splitting on commas.
- Remove duplicates, fix names, handle gaps.
- Total units and orders, take the top K.
- Give the answer and your assumptions.
- Parse the text into rows before any cleaning.
- Cleaning removes duplicates and fixes spelling and missing values.
- Aggregation counts units and orders per product.
- Report the answer together with the assumptions you made.
Knowing it is half the job. Saying it is the other half.
Interview Clozo is an AI interview copilot for real interview rounds: it hears the question and puts a strong answer on your screen, and you say it in your own words. See the features or how it works.
Start Free Trial →Worked example
The input is a ten-row order file (illustrative) with four planted problems: a quoted field with a comma, a missing quantity, one exact duplicate row, and inconsistent spacing in product names. The script parses it with the function above, then cleans and aggregates it.1
| Quantity | Value |
|---|---|
| Rows parsed | 10 |
| Rows garbled by a plain comma split | 2 |
| Rows after removing the exact duplicate | 9 |
| Rows after dropping the missing quantity | 8 |
| Distinct product spellings, before and after cleaning | 6 and 4 |
| Units: widget, gadget, cable, gizmo | 6, 6, 4, 1 |
| Orders: widget, gadget, cable, gizmo | 3, 2, 2, 1 |
| Mean quantity per row | 2.125 |
| Median quantity per row | 2 |
| Population standard deviation | 0.927 |
| Sample standard deviation | 0.991 |
By units, widget and gadget tie at six, so a top-one answer needs a tie-break: alphabetical order gives gadget. By orders, widget leads with three and gadget and cable tie at two, so the top two by orders depend on the tie-break: alphabetical gives widget and cable.1 The same question has different defensible answers until you name the measure and the tie-break.
The eight kept quantities are 3, 2, 1, 2, 4, 2, 1 and 2, which sum to 17, so the mean is 17 divided by 8, or 2.125. Sorted, the middle two are both 2, so the median is 2. The squared distances from the mean sum to 6.875: dividing by 8 and taking the square root gives 0.927, while dividing by 7 gives 0.991.1
Text description of the diagram
- Widget and gadget tie at six units.
- Widget leads on orders with three.
Trade-offs and edge cases
Every cleaning rule is a modelling decision. Dropping a row with a missing quantity leaves that order out of every count. Filling with zero pulls the mean down. Filling with a typical value keeps the mean but shrinks the standard deviation, so it hides the gap. Asking the interviewer removes the guess and is the right first move.
Text description of the diagram
- Dropping the row leaves that order out of every count.
- Filling with zero pulls the mean down.
- Filling with a typical value keeps the mean but shrinks the standard deviation.
- Asking the interviewer removes the guess.
Other edge cases to test before you are asked: an empty input, a header with no data, a field holding a line break inside quotes, a quantity that is text instead of a number, a negative quantity, and Windows line endings. Python's csv module handles quoting and line breaks for you, which is why it beats a hand parser for real work; a hand parser is for showing that you understand the rules.
Reported practice differs on whether to use a library at all: some interviewers allow csv or pandas, others want a parser written by hand. Ask early. Note too that a second question in the same loop is reported to be machine learning (ML) coding, so it helps to also rehearse domain-flavoured implementation tasks, evaluation metrics from scratch and the wider AI engineer coding questions.
If the interviewer allows pandas
With the pandas library, the four stages become a short chain of calls. read_csv parses the text, drop_duplicates removes exact repeats, str.strip().str.casefold() on the product column normalises names, and dropna or fillna applies your missing-value rule. Then groupby('product')['qty'].agg(['sum','count']) gives units and orders in one table, and nlargest takes the top K. The same chain extends to a total per category or a rolling window over dates. The library does not make the decisions for you. You still state the measure, the tie-break and the missing-value rule, check how equal values are ordered, and say how many rows each step removed.
How to answer it in an interview
Here is a CSV string of orders. Rank the best-selling products, give me the top K, and the average quantity per order.
First I would confirm what top K means: units or orders, and how ties are broken. I parse with a real CSV reader, because quoted fields can contain commas. Then I drop exact duplicate rows, trim and lower-case product names, and drop rows with a missing quantity, telling you how many that removes. I total units per product in a counter and take the K largest with a heap or a sort. I report the mean, say whether my standard deviation is the population or the sample version, and test on a row with a quoted comma.
The spoken structure: clarify the measure, parse correctly, clean with stated rules, aggregate, then report assumptions. Treat your own edge-case choices the way a reviewer would; the code review questions show what a careful reader looks for.
Common mistakes
- "I split each line on commas." (wrong) A quoted field can hold a comma. (right) "I use a CSV reader, or a parser that tracks quotes."
- "Top K most sold is obvious." (wrong) It could mean units or orders. (right) "I will rank by units, and break ties alphabetically by name; say if you want orders."
- "I removed the bad rows." (wrong) Silent loss hides bias. (right) "I dropped one row with a missing quantity and kept eight of ten."
- "The standard deviation is 0.99." (wrong) It does not say which version. (right) "The sample standard deviation is 0.991; the population one is 0.927."
- "I count product names as they are." (wrong)
widgetandWidgetcount as two products. (right) "I trim and fold case before counting."
Follow-up questions
How do you rank the best-selling products from a CSV string?
Parse the rows, clean them, total the quantity per product in a counter, and take the K largest by total with a heap or a sort. State the measure and the tie-break (alphabetical by name, say). To group per category or over a rolling window, add that key or window to the grouping step and keep the rest of the pipeline.
What does 'top K best-selling' mean: units or orders?
Units sums the quantities; orders counts the rows. In the worked example widget and gadget tie at six units, but widget has three orders and gadget two, so the choice changes the ranking. With an alphabetical tie-break, the top two by orders are widget and cable.
What should you do with gaps, mixed formats and repeated rows?
Remove exact duplicates, normalise text and number formats, and apply an explicit missing-value rule that you state. Report how many rows each step removed.
Why not just split a CSV line on commas?
Because a quoted field can contain commas and even line breaks, and a plain split cuts it into extra fields. In the example it garbles two of ten rows.
Population or sample standard deviation: which do you report?
Report the sample version when the rows are a sample of a larger process, and the population version when they are the whole set. Always name the one you used.
- The data-parsing round is parse, clean, aggregate, report, and it is graded on edge cases and stated assumptions.
- Never split CSV on commas; track quotes or use the
csvmodule withnewline=''. - Fix the measure for top K, units or orders, and fix the tie-break.
- Count rows after each cleaning step and tell the interviewer what was dropped.
- Say whether your standard deviation is the population or the sample version.
Sources
- csv: CSV File Reading and Writing (Python 3 documentation) — Python Software Foundation, 26 Oct 2026
- RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files — IETF (Shafranovich), 1 Oct 2005
- heapq: Heap queue algorithm (Python 3 documentation) — Python Software Foundation, 26 Oct 2026