I want to know which one is better in terms of "time complexity" from these two:
for(int i=0;i<n;i++){
s=s+"0";
}
and
for(int i=0;i<n;i++){
s+="0";
}
I was solving a question and I found "TLE(Time Limit Exceed)" while using first approach but it worked for second one.
The first one creates an intermediate string (that will be assigned to s
after the +
operation), whereas the second one may not (depends on the capacity of the string).
The complexity in worst case is the same in both case, in best case, it's just copying the new string for the second case against a full copy of both strings for the first case (+memory allocation and free).
The fact that your get TLE
(Time Limit Exceeded) is probably due to this worst case all the time, always copying huge strings instead of just adding something to the existing one (without reallocation). Like vector, there should be some heuristic in string
to get adequate capacity in advance.
As @Slava said, this example should be written differently, I suppose the actual code is different.