You need to build one long string by appending pieces inside a loop. Why can the naive approach get slow, and how do you fix it?
technical-conceptual · Junior level · software-engineering
What the interviewer is really asking
Checks whether the candidate understands string immutability and the hidden O(n^2) cost of loop concatenation, plus the standard fix.
What to say
- Explain that in most mainstream languages strings are immutable, so each `result += piece` allocates a new string and copies all the characters accumulated so far — over n iterations that copying sums to O(n^2).
- Give the fix: collect the pieces in a list/buffer and join once at the end (`''.join(parts)` in Python, `String.join` / `StringBuilder.append` then `toString()` in Java), which is O(n) total because each character is copied a constant number of times.
- Note this only matters at scale — for a handful of concatenations the difference is invisible, so reach for a buffer when the loop count grows with input size.
What to avoid
- Claim `+=` is fine everywhere because 'the compiler optimizes it' — that's true for a single expression but not for a loop that rebinds the variable each pass.
- Say strings are mutable and the append happens in place — they aren't in Python, Java, JavaScript, or C#.
- Reach for a buffer for two or three concatenations where it adds noise for no measurable gain.
Example answers
Strong: Strings are immutable, so `s += chunk` in a loop builds a brand-new string each pass and copies everything so far — that's 1 + 2 + ... + n character copies, which is O(n^2). I switch to collecting chunks in a list and calling `''.join(parts)` once, which is O(n). I hit this on a report exporter that concatenated 50k rows and took 40 seconds; the join version finished in under one.
Weak: I'd just use `+=` in the loop — string concatenation is basically free, and if it were slow the language would handle it for me.
Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.