โ† Back to Index

๐Ÿ“š Reorganize String โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Reorganize String problem involves rearranging the characters of a string so that no two adjacent characters are the same. If it is not possible, return an empty string.

This problem can be efficiently solved using a max-heap to track the most frequent characters.

๐Ÿงฑ Pattern Template

class Solution {
    public String reorganizeString(String s) {
        Map<Character, Integer> frequencyMap = new HashMap<>();
        for (char c : s.toCharArray()) {
            frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
        }

        PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(
            (a, b) -> b.getValue() - a.getValue()
        );
        maxHeap.addAll(frequencyMap.entrySet());

        StringBuilder result = new StringBuilder();
        Map.Entry<Character, Integer> prev = null;

        while (!maxHeap.isEmpty()) {
            Map.Entry<Character, Integer> current = maxHeap.poll();
            result.append(current.getKey());

            if (prev != null && prev.getValue() > 0) {
                maxHeap.offer(prev);
            }

            current.setValue(current.getValue() - 1);
            prev = current;
        }

        return result.length() == s.length() ? result.toString() : "";
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Reorganize String

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

Explanation:
- The most frequent character is 'a'.
- Alternate 'a' with 'b' to ensure no two adjacent characters are the same.

๐Ÿ’ก Pro Tips