<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) {
        vector<int> freq(26, 0);
        
        // Count frequency of each character
        for (char c : s) {
            freq[c - 'a']++;
        }
        
        // Create a max heap (priority queue) based on character frequency
        priority_queue<pair<int, char>> pq;
        for (int i = 0; i < 26; ++i) {
            if (freq[i] != 0) {
                pq.push({freq[i], i + 'a'});
            }
        }
        
        string ans;
        pair<int, char> prev = {-1, '#'}; // Keeps track of the previously used character
        
        // Loop until the priority queue is empty
        while (!pq.empty()) {
            // Pop the most frequent character
            auto cur = pq.top();
            pq.pop();
            
            // Add the current character to the result
            ans.push_back(cur.second);
            
            // If there's a previous character waiting, push it back into the queue
            if (prev.first > 0) {
                pq.push(prev);
            }
            
            // Update the current character's frequency and mark it as "previous" for the next iteration
            cur.first--;
            prev = cur;
        }

        if (ans.size() != s.size()) return "";
        
        return ans;
    }
};

8700