Data Structures & AlgorithmsHardWipro · Accenture pattern

What is the time complexity of this Java method?

What is the time complexity of this Java method?
String build(int n) {
    String s = "";
    for (int i = 0; i < n; i++)
        s = s + "a";
    return s;
}
  1. A. O(1)
  2. B. O(n)
  3. C. O(n²)
  4. D. O(n log n)

Correct answer: C. O(n²)

Java Strings are immutable, so each s + "a" copies the current i characters into a new String: 1 + 2 + … + n = n(n + 1)/2 character copies, O(n²). A StringBuilder would make it O(n) amortised.

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

Exams that ask this topic