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

What to avoid

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.