Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1405. Longest Happy String #193

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions 1405. Longest Happy String
Original file line number Diff line number Diff line change
@@ -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<int, char>;
priority_queue<pic> 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;
}
};