Reorganize String
Master this topic with zero to advance depth.
Reorganize String
Rearrange string so no two adjacent characters are identical.
Visual Representation
s = "aaabcc"
a: 3, b: 1, c: 2
1. Fill 'a' at 0, 2, 4 -> [a, _, a, _, a, _]
2. Fill 'c' at 1, 3 -> [a, c, a, c, a, _]
3. Fill 'b' at 5 -> [a, c, a, c, a, b]Examples
Interleaving 'a' and 'b' satisfies the requirement.
Level I: Brute Force (All Permutations)
Intuition
Generate all possible permutations of the input string and check if any of them satisfy the condition that no two adjacent characters are identical.
Thought Process
- Use recursion to generate all permutations.
- For each unique permutation, check adjacency:
s[i] == s[i+1]. - Return the first valid permutation found, or "" if none exist.
Detailed Dry Run
s = "aab" Permutations: ["aab", "aba", "baa"]
- "aab": a == a (FAIL)
- "aba": a != b, b != a (SUCCESS). Return "aba".
Level II: Greedy with Max-Heap
Intuition
Always pick the most frequent character that is different from the last one placed. A Max-Heap allows us to fetch the highest frequency character efficiently.
Thought Process
- Count frequencies and push into a Max-Heap
(count, char). - In each step, pop the top character.
- Add it to the result and keep it aside (don't push back yet) because we can't use it in the very next step.
- Push the character from the previous step back into the heap if it still has remaining count.
Pattern: Priority Queue / Interleaving
Detailed Dry Run
s = "aaabcc" Heap: [(a,3), (c,2), (b,1)]
- Pop (a,3). Res: "a". prev=(a,2)
- Pop (c,2). Res: "ac". Push prev (a,2). prev=(c,1)
- Pop (a,2). Res: "aca". Push prev (c,1). prev=(a,1) Result: "acacab"
Level III: Optimal Greedy (Frequency Interleaving)
Intuition
Place the most frequent character at even indices (0, 2, 4...). If it fits, we can always interleave the rest.
Thought Process
- Count frequencies. If any char count , impossible.
- Start with the most frequent char.
- Fill indices 0, 2, 4... then wrap to 1, 3, 5...
Pattern: Frequency-Based Positioning
Detailed Dry Run
s = "aab" Max char 'a' count = 2. Place at 0, 2. [a, _, a] Next char 'b' count = 1. Place at 1. [a, b, a]
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.