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 an empty string if no such arrangement is possible.
Example:
Input: s = "aab"
Output: "aba"
Input: s = "aaab"
Output: ""
s
?
1 <= len(s) <= 500
.Here is the Python solution to the problem:
from collections import Counter
import heapq
def reorganizeString(s: str) -> str:
# Count frequency of each character
frequency = Counter(s)
# Create a max heap with negative frequencies (heapq is min heap by default in Python)
max_heap = [(-count, char) for char, count in frequency.items()]
heapq.heapify(max_heap)
previous_char, previous_count = None, 0
result = []
while max_heap:
count, char = heapq.heappop(max_heap)
# Add the previous character back if it has remaining count
if previous_char and previous_count < 0:
heapq.heappush(max_heap, (previous_count, previous_char))
# Append current character to result
result.append(char)
previous_char = char
previous_count = count + 1 # Decrement the frequency count since it's negative
# Join list to form the final string
result = ''.join(result)
# Check if the rearrangement is valid
for i in range(1, len(result)):
if result[i] == result[i - 1]:
return ""
return result
# Example usage
s1 = "aab"
s2 = "aaab"
print(reorganizeString(s1)) # Output: "aba"
print(reorganizeString(s2)) # Output: ""
n
is the length of the string s
. This complexity arises due to the heap operations (insert and extract).This solution ensures that we can reorganize the string such that no two adjacent characters are the same, or determine that it is not possible.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?