> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Reorganize String Python Solution with Tests

> Tested Python solution for LeetCode 767 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 767, Medium. Topics: Hash Table, String, Greedy, Sorting, Heap (Priority Queue), Counting. [View on LeetCode](https://leetcode.com/problems/reorganize-string/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 767   # by problem number
lcpy gen -s reorganize_string   # by problem name
```

## Problem

Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same.

Return *any possible rearrangement of* `s` *or return* `""` *if not possible*.

### Examples

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

```
Input: s = "aaab"
Output: ""
```

### Constraints

* 1 \<= s.length \<= 500
* `s` consists of lowercase English letters.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/reorganize_string/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/reorganize_string/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heapq
from collections import Counter


class Solution:
    # Time: O(n log k)
    # Space: O(k)
    def reorganize_string(self, s: str) -> str:
        counts = Counter(s)
        # Impossible when the most frequent char cannot be placed apart.
        if max(counts.values()) > (len(s) + 1) // 2:
            return ""

        # Max-heap by remaining count (negate for Python's min-heap).
        heap: list[tuple[int, str]] = [(-count, char) for char, count in counts.items()]
        heapq.heapify(heap)

        result: list[str] = []
        while len(heap) >= 2:
            neg_count_a, char_a = heapq.heappop(heap)
            neg_count_b, char_b = heapq.heappop(heap)
            result.append(char_a)
            result.append(char_b)
            if neg_count_a + 1 < 0:
                heapq.heappush(heap, (neg_count_a + 1, char_a))
            if neg_count_b + 1 < 0:
                heapq.heappush(heap, (neg_count_b + 1, char_b))

        if heap:
            result.append(heap[0][1])

        return "".join(result)
```

## Complexity

| Time       | Space |
| ---------- | ----- |
| O(n log k) | O(k)  |

## Tags

[NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
