I tried appending character to end of the string using + operator to a coding problem .That solution was giving memory limit exceeded. Then I saw solutions using += to append character. Is there any difference between the two in case of time complexity or memory complexity ?
Example - My solution
string arrangeWords(string text) {
text[0] = text[0] + 32;
text = text + ' ';
string temp = "";
map < int, vector < string >> mp;
for (char c: text) {
if (c != ' ')
temp = temp + c; //---Notice this line
else {
mp[temp.size()].push_back(temp);
temp = "";
}
}
string res = "";
for (auto it: mp)
for (auto j: it.second)
res = res + j + ' '; //----Notice this line
res[0] = toupper(res[0]);
return res.substr(0, res.size() - 1);
}
Accepted Solution -
string arrangeWords(string text) {
text[0] += 32;
text += ' ';
string temp = "";
map < int, vector < string >> mp;
for (char c: text) {
if (c != ' ')
temp += c; //Notice this line change
else {
mp[temp.size()].push_back(temp);
temp = "";
}
}
string res = "";
for (auto it: mp)
for (auto j: it.second)
res += j + ' '; //Notice this line change
res[0] = toupper(res[0]);
return res.substr(0, res.size() - 1);
}
temp = temp + c;
creates a temporary temp + c
(which would probably require (slow) allocation) before to assign to temp
. (Complexity is O(n))
temp += c;
reuse buffer if large enough (complexity O(1)), else reallocation should be done (and then, it would be "similar" to above method) (complexity O(n)). (amortized complexity is O(1)
)
In addition, less allocation occurs, less chance to have fragmented memory.