I am trying to solve Sort Characters By Frequency on LeetCode. The first used Binary Operator gives me a TLE, but when I use a compound assignment operator then it works fine. But I don't understand why.
Is there any logic behind it? I'm attaching both codes below so you can try it for yourself.
This gives TLE
class Solution {
public:
string frequencySort(string s) {
unordered_map<char, int> m;
for(int i = 0; i < s.length(); i++)
m[s[i]]++;
priority_queue<pair<int, char>> pq; // maxheap based on frequency
for(auto x = m.begin(); x != m.end(); x++)
pq.push(make_pair(x->second, x->first));
string ans = "";
while (!pq.empty())
{
for(int i = 0; i < pq.top().first; i++)
ans = ans + pq.top().second;
pq.pop();
}
return ans;
}
};
This works fine
class Solution {
public:
string frequencySort(string s) {
unordered_map<char, int> m;
for(int i = 0; i < s.length(); i++)
m[s[i]]++;
priority_queue<pair<int, char>> pq; // maxheap based on frequency
for(auto x = m.begin(); x != m.end(); x++)
pq.push(make_pair(x->second, x->first));
string ans = "";
while (!pq.empty())
{
for(int i = 0; i < pq.top().first; i++)
ans += pq.top().second;
pq.pop();
}
return ans;
}
};
ans = ans + pq.top().second;
creates a temporary string which is then moved toans
. Unless small string optimization applies, each operation involves memory allocation and de-allocation.ans += pq.top().second;
does not create a temporary, and memory is allocated only if the memory previously reserved byans
is exhausted - which happens far less often.