<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 freq[26]={0};
        for(int i=0;i<s.length();i++){
            char ch=s[i];
            freq[ch-'a']++;
        }
        int n=s.length();
        priority_queue<pair<int, char>> pq;
        for (int i = 0; i < 26; i++) {
            if (freq[i] > 0) {
                // If any character's frequency is greater than (n+1)/2, return ""
                if (freq[i] > (n + 1) / 2) {
                    return "";
                }
                pq.push({freq[i], i + 'a'});
            }
        }
        string ans="";
        while(pq.size()>1){
            char firstChar=pq.top().second;
            int firstFreq=pq.top().first;
            firstFreq--;
            pq.pop();
            char secondChar=pq.top().second;
            int secondFreq=pq.top().first;
            secondFreq--;
            pq.pop();
            ans.push_back(firstChar);
            ans.push_back(secondChar);
            if(firstFreq>0){
                pq.push(make_pair(firstFreq,firstChar));
            }
            if(secondFreq>0){
                pq.push(make_pair(secondFreq,secondChar));
            }
        }
        if(pq.size()==1){
            char firstChar=pq.top().second;
            int firstFreq=pq.top().first;
            firstFreq--;
            ans.push_back(firstChar);
            pq.pop();
            if(firstFreq!=0){
                return "";
            }
        }
        return ans;
    }
};
8200