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?
inputString
is a variable, therefore so isinputString.length
. It must be factored in. – HemicycleinputString
so I don't know why one's being imagined. You could do that with any variable in any Big-O analysis ever. "Well, if the size of an array is bounded, then technically O(n log n) sorting is O(1). Oh, and if the size of a linked list is bounded then technically O(n) search is O(1). Oh, and..." Why say those things? They're pointless statements. – Hemicycle