The answer is wrong in two ways. O(xn^2) doesn't exist. In big O you drop all constants. It would be O(n^2) if that was right (it isn't).
The next part depends on language, the implementation of + on strings and the string class itself. If the string class is mutable, then + should be O(n) assuming it has a decent implementation (doesn't cause a reallocatiion and copy on each use of +). If the string class is immutable, it depends on how the String is implemented- does it use a single character buffer for all data, or can it handle multiple character pointers in an ordered list? Of course even on the worst implementation it wouldn't be O(n^2), more like O(2n) which is O(n) (2 copies per iteration). Anyone giving me an answer of O(n^2) would be marked wrong. But really any modern String class implementation would be O(n) without a constant and be pretty much O(n*l) in space (where n is the number of words and l is the average word length).
class String {
String base; //used for appended strings
String additional; //used for appended strings
char baseData[]; //used for pure strings
String(String base, String additional) {
this.base = base;
this.additional = additional;
}
operator + (String newString) {
return new String(this, newString);
}
//As an example of how this works
int length() {
if(base != null) {
return base.length()+additional.length(); //This can be cached, and should be for efficiency.
}
else {
return baseData.length;
}
}
}
Notice that + is O(1). Yes, I know Java doesn't have operator overloading, the function is there to show how its implemented.