Data Structures & AlgorithmsModerateTCS Digital · Infosys SP

A string s has length n. What is the time complexity of building s by repeated concatenation s = s + c in a language with immutable strings (no optimisation), for n characters?

  1. A. Θ(n)
  2. B. Θ(n²)
  3. C. Θ(1) per step, Θ(n) total
  4. D. Θ(n log n)

Correct answer: B. Θ(n²)

Each concatenation copies the whole current string, so the costs are 1 + 2 + … + n = Θ(n²). A builder or list-and-join brings it down to Θ(n).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic