ProgrammingHardAmazon OA · Flipkart coding round

A program builds a long output string with `s = s + str(i) + ' '` for each of n = 2 * 10^5 values i. Which change is the standard fix for Python?

  1. A. Replace str(i) with repr(i) for each piece
  2. B. Use s += in a nested loop so Python reuses the buffer
  3. C. Convert the whole string to a bytearray before each addition
  4. D. Collect the pieces in a list and call ' '.join(parts) once at the end

Correct answer: D. Collect the pieces in a list and call ' '.join(parts) once at the end

Building an immutable str by repeated concatenation can copy the whole string each time, which is quadratic in the worst case. Appending to a list and joining once is linear.

More Python Programming questions

Exams that ask this topic