Search code examples
javastringbuilder

Why StringBuilder.append time complexity is O(1)


By amortized analysis, we know that N insertions with StringBuilder#append method take O(N) time. But here is where I get lost. Consider this where inputString is an input string from a user.

for (int i = 0; i < N; i++) {
   s.append(inputString); 
   // where s is an empty StringBuilder object at the beginning 
   // and inputString is the string that is taken from the user
}

Should this have time complexity of O(inputString.length * N), since append() copies the input string to the end of the StringBuilder N times? Why do we consider that append() takes O(1) time complexity whereas it should be considered as O(inputString.length)?

Nearly everywhere I check, it is considered as O(1), such as https://quora.com/What-is-the-complexity-of-Java-StringBuffer-append as well as What is the complexity of this simple piece of code?


Solution

  • Should this have time complexity of O(inputString.length * N) since append() copies the input string to the end of the StringBuilder N times?

    Yes.

    Why do we consider that append() takes O(1) time complexity whereas it should be considered as O(inputString.length)?

    It is O(1) when appending single characters. A StringBuilder is like an ArrayList. When you append a single item the cost is O(1). Appending a string is like calling addAll()--the cost is proportional to the length of the string / the number of items being added.

    It appears you understand everything correctly. The problem is people are often sloppy when discussing Big-O performance. It's endemic.