Is shorthand operator fast with strings?

Solution 1
Solution 2
Solution 1 has the line: n[s]=n[s]+s[i]
Solution 2 has the line: n[s]+=s[i]

Here s and ns are strings. All other lines are identical. Both solutions are in C++. 1st solution gives TLE for 2 cases whereas 2nd passes all.

Very easy to see. Look at the documentation for += and +. += appends the character ( O(1) ) and = + makes a new string and assigns it ( O(length of RHS)

1 Like