11. Reorganize String

Given a string s, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result. If not possible, return the empty string.

Example 1:

Input: s = "aab"
Output: "aba"

Example 2:

Input: s = "aaab"
Output: ""

Solution: (Priority Queue)

class Solution
{
public:
    string reorganizeString(string s)
    {

        unordered_map<char, int> m;
        priority_queue<pair<int, char>, vector<pair<int, char>>> pq;

        for (int i = 0; i < s.length(); i++)
        {
            m[s[i]]++;
        }

        for (auto itr = m.begin(); itr != m.end(); itr++)
        {
            pq.push({itr->second, itr->first});
        }
        
        string res = "";

        while (!pq.empty())
        {
            pair<int, char> p1 = pq.top();
            pair<int, char> p2;
            pq.pop();
            res += p1.second;
            
            if (!pq.empty())
            {
                p2 = pq.top();
                pq.pop();
                res += p2.second;
            }

            if (p1.first - 1 > 0)
            {
                pq.push({p1.first - 1, p1.second});
            }

            if (p2.first - 1 > 0)
            {
                pq.push({p2.first - 1, p2.second});
            }
        }

        for (int i = 1; i < res.length(); i++)
        {
            if (res[i] == res[i - 1])
            {
                return "";
            }
        }

        return res;
    }
};

Last updated