<p>Given a string <code>s</code>, rearrange the characters of <code>s</code> so that any two adjacent characters are not the same.</p>

<p>Return <em>any possible rearrangement of</em> <code>s</code> <em>or return</em> <code>&quot;&quot;</code> <em>if not possible</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> "aba"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "aaab"
<strong>Output:</strong> ""
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 500</code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

class Solution {
public:
    string reorganizeString(string s){
        int n = s.size();
        map<char, int> mp;

        // Count frequency of each character
        for (auto val : s){
            mp[val]++;
        }
    
        // Max heap to store characters by frequency
        priority_queue<pair<int, char>> pq;
        for (auto [ch, freq] : mp){
            pq.push({freq, ch});
        }

        string result = "";
        pair<int, char> prev = {0, '#'}; // {frequency, character}, initially invalid

        while (!pq.empty()){
            auto [freq, ch] = pq.top();
            pq.pop();

            // Add the current character to the result
            result += ch;
            freq--;

            // If the previous character can still be used, push it back into the heap
            if (prev.first > 0) {
                pq.push(prev);
            }

            // Update prev to the current character
            prev = {freq, ch};
        }

        // Check if the result is valid
        if (result.size() != s.size()){
            return "";
        }

        return result;
    }
};
9500