ProgrammingVery hardAmazon OA · Goldman Sachs OA

Strings are immutable here, so s = s + "a" copies the whole current string. What is the time complexity of the following pseudocode, as a function of n?

Strings are immutable here, so s = s + "a" copies the whole current string. What is the time complexity of the following pseudocode, as a function of n?
String s = ""
for (each i from 1 to n)
    s = s + "a"
end for
  1. A. O(n²)
  2. B. O(n)
  3. C. O(n log n)
  4. D. O(1)

Correct answer: A. O(n²)

Iteration i copies a string of length i − 1, so the total copying is 0 + 1 + … + (n − 1) ≈ n²/2: O(n²). Using a growable buffer instead brings it down to O(n).

More Pseudocode and Code Tracing questions

Exams that ask this topic