Fix a Row-to-CSV Converter: Output Correctness and Efficiency
StringsAuto-graded · 20 test casesLast updated
Tests whether a candidate can spot a trailing-comma output bug and a quadratic string-building performance problem, then write a correct, efficient fix.
Fix a Row-to-CSV Converter: Output Correctness and Efficiency
You are maintaining a data-export utility that serializes a table of string fields into CSV text so a downstream system can import it. A colleague wrote the first version of the function, but it has two distinct problems — one in the output it produces, and one in how it scales.
Below is the buggy Python implementation you have been handed:
def build_csv(rows):
result = ""
for row in rows:
for field in row:
result += field + ","
result += "\n"
return result
Your tasks:
- Identify the output bug. Describe exactly what the function produces that differs from the required format, and give a concrete example.
- Identify the performance bug. Explain why the function slows down sharply on large inputs, and characterise the cost in terms of how many characters are copied as the output grows.
- Write a corrected function
fix_csv_exportthat produces the right output efficiently.
Required Output Format
- One line per row, fields joined by a single comma, no trailing comma.
- Every line, including the last, ends with a newline character
\n. - An empty row (a list with no fields) produces an empty line: just
\n.
Constraints
0 ≤ len(rows) ≤ 10^40 ≤ fields per row ≤ 10^3- Each field is a non-empty string containing no commas, double-quotes, or newline characters.
- No field is
None. - If
rowsis empty, return an empty string"". - The total number of characters across all fields fits comfortably in memory.
Examples
Example 1
Input: fix_csv_export([['id', 'name'], ['1', 'Ada']])
Output: 'id,name\n1,Ada\n'
Example 2
Input: fix_csv_export([['a', 'b', 'c'], ['1', '2', '3']])
Output: 'a,b,c\n1,2,3\n'
Example 3
Input: fix_csv_export([[]])
Output: '\n'
Example 4
Input: fix_csv_export([['only']])
Output: 'only\n'
Hints
Hint 1
Trace through what the inner loop appends after the last field in a row — is there anything extra that should not be there?
Hint 2
Repeated string concatenation inside a loop copies the entire accumulated string on every iteration. How does the total work scale with output length? What Python tool builds a sequence of strings in O(n) total time instead?
Hint 3
Python's str.join() solves both problems at once: it places the separator only between items (never after the last one), and it measures all pieces up front before copying anything.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two bugs in the original
Output bug — trailing comma after every field.
The inner loop appends a comma unconditionally after every field, including the last one in each row. For the row ["id", "name"] the loop produces id,name, before appending \n, giving id,name,\n instead of id,name\n. The fix is to place commas between fields, not after each one.
Performance bug — quadratic string concatenation.
Python strings are immutable. Every result += something creates a brand-new string by copying all previously accumulated characters plus the new piece. If the final output is N characters long, the total number of characters copied across all iterations is proportional to 1 + 2 + 3 + … + N = O(N²). On a large export this becomes the dominant cost and the function grinds to a halt.
The fix
str.join(iterable) measures every piece in the iterable first, allocates one buffer of exactly the right size, and then copies each piece once — O(N) total work. It also places the separator only between items, so no trailing comma is ever added.
The corrected function builds each line with ','.join(row) (correct separator placement) appends '\n', and then collects all lines with a single outer ''.join(...). Because the outer join receives a generator, nothing is materialised until join itself runs, keeping memory usage proportional to the output size.
Edge cases
| Input | Output | Why |
|---|---|---|
[] | "" | The generator yields nothing; ''.join(...) on an empty iterable is "". |
[[]] | "\n" | ','.join([]) is "", so the line is "" + "\n" = "\n". |
[["only"]] | "only\n" | Single-element join adds no comma. |
Complexity
- Time: O(N) where N is the total number of characters in the output.
- Space: O(N) for the returned string; the generator avoids building intermediate lists.
Reference solution
from typing import List
def fix_csv_export(rows: List[List[str]]) -> str:
return ''.join(','.join(row) + '\n' for row in rows)