diff --git a/1405. Longest Happy String b/1405. Longest Happy String new file mode 100644 index 00000000..90e04103 --- /dev/null +++ b/1405. Longest Happy String @@ -0,0 +1,43 @@ +Leetcode Question +Problem No.1405 Longest Happy String +Problem Link- https://leetcode.com/problems/longest-happy-string?envType=daily-question&envId=2024-10-16 + +Solution in C++ +class Solution { +public: + string longestDiverseString(int a, int b, int c) { + string res; //Stores Longest happy string + using pic = pair; + priority_queue maxheap; + if(a>0) maxheap.push({a,'a'}); + if(b>0) maxheap.push({b,'b'}); + if(c>0) maxheap.push({c,'c'}); + + //Try forming max length string as per constraint + while(!maxheap.empty()){ + auto [count,character] = maxheap.top(); + maxheap.pop(); + + int n=res.size(); + //Check if the current character has occurred in previous 2 indices + if(n>=2 and res[n-1]==character and res[n-2]==character){ + if(maxheap.empty()) + break; + + auto [nextCount,nextCharacter] = maxheap.top(); + maxheap.pop(); + + res.push_back(nextCharacter); + nextCount--; + if(nextCount>0) + maxheap.push({nextCount,nextCharacter}); + }else{ + count--; + res.push_back(character); + } + if(count>0)//Re-push the current character only if it has 1+ frequency + maxheap.push({count,character}); + } + return res; + } +};