I\'m pasting this text from an ebook I have. It says the complexity if O(n2) and also gives an explanation for it, but I fail to see how.
Question: What i
Looks like O(n) to me (with n being the total number of letters in all the words). You're basically iterating over every character in words to append it into the StringBuffer.
The only way I could see this as being O(n^2) is if append() iterates all the contents in the buffer before appending any new characters. And it may actually do this occasionally if the number of characters exceeds the currently allocated buffer length (it has to allocate a new buffer, and then copy everything from the current buffer into the new buffer). But it won't happen on every iteration, so you still won't have O(n^2).
At most you'd have O(m * n), where m is the number of times the buffer length is increased. And because the StringBuffer will double its buffer size every time it allocates a larger buffer we can determine that m is roughly equal to log2(n) (actually log2(n) - log2(16), since the default initial buffer size is 16 instead of 1).
So the real answer is that the book's example is O(n log n), and that you can get it down to O(n) by preallocating a StringBuffer with a capacity large enough to hold all of your letters.
Note that in Java appending to a string using += does exhibit the inefficient behavior described in the book's explanation, as it has to allocate a new string and copy all the data from both strings into it. So if you do this, it is O(n^2):
String sentence = "";
for (String w : words) {
sentence += w;
}
But using StringBuffer should not generate the same behavior as in the above example. That's kind of one of the major reasons for StringBuffer to exist in the first place.