KatInterview

Fix a Row-to-CSV Converter: Output Correctness and Efficiency

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringsstringsperformancejoins

Last 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:

  1. Identify the output bug. Describe exactly what the function produces that differs from the required format, and give a concrete example.
  2. 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.
  3. Write a corrected function fix_csv_export that 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^4
  • 0 ≤ 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 rows is 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.