ProgrammingHardProduct-company MCQ pattern

Which call builds one string from n pieces in O(total length) time?

  1. A. sum(pieces, '')
  2. B. functools.reduce(lambda a, b: a + b, pieces, '')
  3. C. a loop that does s = s + p for each piece p
  4. D. ''.join(pieces)

Correct answer: D. ''.join(pieces)

join sums the lengths first and copies each piece once. sum() refuses a string start value with a TypeError, and repeated + copies the growing result each time, which is O(n squared) in the worst case.

More Python Programming questions

Exams that ask this topic