Wednesday, August 23rd

 Reorganize a string

Given a string, rearrange the characters so that no 2 adjacent characters are the same


The idea is to use a priority queue to repeatedly use the characters of higher frequencies.  To ensure no 2 adjacent characters are the same, we remove a character from both of the top 2 elements in a priority queue

To populate the priority queue based on character occurrences, we first calculate character frequencies

    vector<int> v(26,0);
for(int i=0; i<s.size(); i++) {
v[s[i]-97]+=1;
}

Then we populate the priority queue with pairs, where the first element is the frequency of a character, and the second element of the pair is the character itself.  With this organization, we can easily use the priority queue's sorting mechanism

priority_queue<pair<int, char> > pq;
for(int i=0; i<26; i++) {
if(v[i]>0) pq.push( make_pair(v[i], i+97) );
}

Initiate the solution string

string sol="";

Now we repeatedly pull characters from the top of the queue, and append the characters to our solution string.

As long as there are 2 or more characters remaining in the queue, we retrieve and then pop the top 2 elements in the priority queue.  We then append each character to the solution string.  Then, if there are 1 or more characters remaining in the character's count, we push the character back onto the priority_queue, decrementing its frequency by 1

    pair<int, char> p1, p2;
while(pq.size()>=2) {
p1=pq.top(); pq.pop();
p2=pq.top(); pq.pop();
sol+=p1.second;
sol+=p2.second;
if(p1.first-1>0) pq.push(make_pair(p1.first-1, p1.second));
if(p2.first-1>0) pq.push(make_pair(p2.first-1, p2.second));
}

Lastly, if a character pair remains in the queue (remember the above while loop operates when there are 2 or more character pairs on the priority queue), then we test the frequency for the character.  If the character pair has a remaining frequency of more than 2, then we return an empty string because we can't properly organize the string.

Otherwise, if there is a character frequency of 1, we append it to the solution string

if(pq.size()) {
if(pq.top().first>1) return "";
sol+=pq.top().second;
}

Finally, return the solution string

return ans;

Kind of tricky converting between integers and characters

Shout out to CHIIKUU for a nice implementation using double tops of the priority queue

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th