String concatenation time complexity S+=X and S = S+X

  c++, concatenation, string, time-complexity

I was solving one the free problem on leetcode and I got the TLE(Time Limit Exceeded) when I used st = st+b instead of st+=b. I though both operations are the same. Are they not. Please elaborate. If there is some other issue then also do mention in the answer.

st is initially an empty string and b is a char

Links to the pictures to be more clear :

Here you can see I used st+=b

Here I used st=st+b

string frequencySort(string s) {
    priority_queue<pair<int,char>> pq;
    unordered_map<char,int> m;
        for(int i = 0;i<s.size();i++)
            m[s[i]]++;
    for(auto x:m)
        pq.push(make_pair(x.second,x.first));
    string st = "";
    while(!pq.empty()){
        int x = pq.top().first;
        char b = pq.top().second;
        while(x--)
        st=st+b;
        
        pq.pop();
    }
    return st;
}

Source: Windows Questions C++

LEAVE A COMMENT