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.
Example 1:
Input: s = "aab" Output: "aba"
Example 2:
Input: s = "aaab" Output: ""
Constraints:
1 <= s.length <= 500s consists of lowercase English letters.This approach utilizes a max heap to always place the character with the maximum frequency next, ensuring that no two adjacent characters are the same. If the character frequency is more than half of the string length, it is impossible to rearrange.
In this solution, we utilize Python's heapq library to simulate a max heap by storing negative frequencies. We arrange the highest frequency characters first and reinsert them with decremented counts after placing another character, ensuring no two adjacent characters are the same.
Java
Time Complexity: O(n log k) where n is the length of the string and k is the number of unique characters. Space Complexity: O(n)
This approach utilizes a direct counting mechanism and attempts to place characters in a greedy manner, utilizing an array to keep track of placement positions for the most frequent characters first.
This C solution determines the most frequent character and places it in even indices. Other characters fill in remaining positions. If at any time the most frequent character cannot be placed, we return an empty string.
C++
Time Complexity: O(n) due to linear scanning and filling. Space Complexity: O(1) since we use a fixed-size count array.
| Approach | Complexity |
|---|---|
| Greedy Heap Approach | Time Complexity: O(n log k) where n is the length of the string and k is the number of unique characters. Space Complexity: O(n) |
| Counting and Greedy Approach | Time Complexity: O(n) due to linear scanning and filling. Space Complexity: O(1) since we use a fixed-size count array. |
Reorganize String • Kevin Naughton Jr. • 78,634 views views
Watch 9 more video solutions →Practice Reorganize String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor