C++ | Construct String with Repeat Limit. | O(n) approach using priority queue
class Solution {\npublic:\n    \n    \n    string repeatString(char ch,int num) {\n        string res="";\n        while(num--)\n            res+=ch;\n        r
class Solution {\npublic:\n    \n    \n    string repeatString(char ch,int num) {\n        string res="";\n        while(num--)\n            res+=ch;\n        return res;\n    }\n    \n    string repeatLimitedString(string s, int repeatLimit) {\n        \n        priority_queue<pair<char,int>> pq;\n        vector<int> freq(26);\n        \n        for(int i=0;i<s.length();i++)\n            freq[s[i]-\'a\']++;\n        \n        for(int i=0;i<26;i++) {\n            if(freq[i]) {\n                char keyElement = (\'a\'+i);\n                pq.push({keyElement,freq[i]});\n            }\n        }\n        \n        string resultString = "";\n        \n        while(pq.size()>1) {\n            \n            char firstChar = pq.top().first;\n            int firstCharCount = pq.top().second;\n            pq.pop();\n            \n            if(firstCharCount<=repeatLimit) {\n                \n                resultString+=repeatString(firstChar,firstCharCount);\n            }\n            else {\n                firstCharCount-=repeatLimit; // 1\n                \n                // pulling out second char. \n                char secondChar = pq.top().first; // a \n                int secondCharCount = pq.top().second; // 4\n                pq.pop(); \n                \n                resultString+= (repeatString(firstChar,repeatLimit)+secondChar); //bba\n                \n                if(--secondCharCount)\n                    pq.push({secondChar,secondCharCount}); //{a:3}\n                if(firstCharCount)\n                    pq.push({firstChar,firstCharCount}); //{b:1}\n                \n            }\n        }\n        \n        if(pq.empty()==false) // contains one element \n                resultString+=repeatString(pq.top().first,min(repeatLimit,pq.top().second));\n        \n        \n        return resultString;\n        \n    }\n};
['C', 'Heap (Priority Queue)']