Back to questions
MiddleDebuggingRare
Why is this string-building loop slow on large input?
This works, but an interviewer flags its complexity on large words.
def join_words(words):
s = ""
for w in words:
s += w + " "
return s.strip()Find and fix the performance bug.
Strings are immutable, so each s += ... builds a brand-new string — O(n²) for n words, slow on large inputs. It is functionally correct, but the complexity is the bug. Fix: return ' '.join(words), which is O(n) and idiomatic.
- Believing
+=on a string mutates a buffer in place - Blaming the trailing space or
stripinstead of repeated allocation - Micro-optimizing the concatenation instead of using
join
- Why does string immutability force a new allocation on each
+=? - When is
io.StringIOor a list-plus-joinpreferable for building text?