Exercise 21 of 30 · intermediate · strings · quadratic · hidden cost · builders
Concatenating immutable strings in a loop
The code
s = ""
for i in range(n):
s = s + "x" # strings are immutable: copies sEach line looks O(1). What is the total?
Count: characters copied.
Measured counts
Table
| n | count |
|---|---|
| 8 | 36 |
| 16 | 136 |
| 32 | 528 |
| 64 | 2,080 |
| 128 | 8,256 |
| 256 | 32,896 |
| 512 | 131,328 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n²) characters copied
- Extra space
- Θ(n)
- Exact count
- 1 + 2 + … + n = n(n + 1)/2
- Strings in C#, Java and Python are immutable: s + "x" allocates a new string and copies all of s.
- Iteration i copies i + 1 characters: n(n + 1)/2 in total.
- StringBuilder (C#, Java), "".join (Python) or std::string::append (amortized O(1) in C++, where strings are mutable) make it Θ(n). CPython sometimes resizes in place as an optimisation, but that is not a language guarantee.
Common mistake: Assuming + on strings is O(1). It is O(length of the result).
Check: measured count ÷ (n²) settles near 0.501 for large n.