> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/greedy/767.-reorganize-string.md).

# 767. 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: ""
```

**Note:**

* `S` will consist of lowercase letters and have length in range `[1, 500]`.

```cpp
// Hashmap + greedy + heap
string reorganizeString(string S) { // time: O(nlogn); space: O(n)
    int len = S.length();
    vector<int> count(26, 0);
    for (char ch : S) {
        if (count[ch - 'a'] > (len + 1) / 2) return "";
        ++count[ch - 'a'];
    }
    priority_queue<pair<int, char> > pq;
    for (int i = 0; i < 26; ++i) {
        if (!count[i]) continue;
        pq.push({count[i], (char)('a' + i)});
    }
    string res;
    while (!pq.empty()) {
        auto t = pq.top(); pq.pop();
        if (res.empty() || t.second != res[res.length() - 1]) {
            res += t.second;
            if (--t.first > 0) pq.push(t);
        } 
        else if (!pq.empty()) {
            auto u = pq.top(); pq.pop();
            res += u.second;
            if (--u.first > 0) pq.push(u);
            pq.push(t);
        } else {
            return "";
        }
    }
    return res;
}
```

```cpp
// Hashmap + greedy + heap
string reorganizeString(string S) { // time: O(nlogn); space: O(n)
    vector<int> count(26, 0);
    for (char ch : S) {
        if (++count[ch - 'a'] > (S.length() + 1) / 2) return "";
    }
    priority_queue<pair<int, char> > pq;
    for (int i = 0; i < 26; ++i) {
        if (!count[i]) continue;
        pq.push({count[i], (char)('a' + i)});
    }
    string res;
    while (pq.size() >= 2) {
        auto t = pq.top(); pq.pop();
        auto u = pq.top(); pq.pop();
        res.push_back(t.second);
        res.push_back(u.second);
        if (--t.first > 0) pq.push(t);
        if (--u.first > 0) pq.push(u);
    }
    if (!pq.empty()) res.push_back(pq.top().second);
    return res;
}
```

{% content-ref url="/pages/-LdCCoVC2GqiWdHrc8nc" %}
[358. Rearrange String k Distance Apart](/practice-of-algorithm-problems/greedy/358.-rearrange-string-k-distance-apart.md)
{% endcontent-ref %}

{% content-ref url="/pages/-Ld9rj8gdXHb5roTo-aK" %}
[621. Task Scheduler](/practice-of-algorithm-problems/greedy/621.-task-scheduler.md)
{% endcontent-ref %}
