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 s

Each line looks O(1). What is the total?

Count: characters copied.

Measured counts

050k1.0e+2k200400ncount
Measured
Table
ncount
836
16136
32528
642,080
1288,256
25632,896
512131,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
  1. Strings in C#, Java and Python are immutable: s + "x" allocates a new string and copies all of s.
  2. Iteration i copies i + 1 characters: n(n + 1)/2 in total.
  3. 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.