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.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a collection of colored beads that you need to string together such that no two beads of the same color are right next to each other. The brute force approach involves exploring every possible order in which you could arrange the beads until you stumble upon a valid sequence.
Here's how the algorithm would work step-by-step:
import itertools
def reorganize_string(input_string):
character_list = list(input_string)
# Generate every possible permutation to check all candidate arrangements exhaustively
for candidate_permutation in itertools.permutations(character_list):
is_arrangement_valid = True
for current_index in range(len(candidate_permutation) - 1):
if candidate_permutation[current_index] == candidate_permutation[current_index + 1]:
is_arrangement_valid = False
break
# Early exit if we find any valid sequence satisfying the no-adjacent-duplicates rule
if is_arrangement_valid:
return "".join(candidate_permutation)
# Return empty string if no valid arrangement exists after exhausting permutations
return ""To successfully rearrange the characters so that no two identical neighbors touch, the optimal strategy prioritizes the most frequently appearing elements. By strategically placing the most common items first and interleaving them with other items, we prevent any potential clumping.
Here's how the algorithm would work step-by-step:
from collections import Counter
def reorganize_string(input_string):
character_counts = Counter(input_string)
# We validate frequency first because any character exceeding half the length makes separation mathematically impossible.
max_allowed_frequency = (len(input_string) + 1) // 2
for char, freq in character_counts.items():
if freq > max_allowed_frequency:
return ""
sorted_characters = sorted(input_string, key=lambda char: (-character_counts[char], char))
result_array = [None] * len(input_string)
current_index = 0
# Alternating placement ensures identical characters are spaced out and never placed adjacently.
for character in sorted_characters:
result_array[current_index] = character
current_index += 2
# Wrapping around ensures remaining slots are filled seamlessly when even indices are exhausted.
if current_index >= len(input_string):
current_index = 1
return "".join(result_array)| Case | How to Handle |
|---|---|
| Empty string or single character string | Return the input string immediately as no adjacent characters can be identical. |
| String with all identical characters like aaa | Detect that the most frequent character exceeds the threshold (n + 1) / 2 and return an empty string. |
| Two character string with identical characters like aa | The frequency check correctly identifies that the count is too high and returns an empty string. |
| Two character string with distinct characters like ab | Place them sequentially into the result array and return the valid reorganized string. |
| Highly skewed frequency where one character dominates like aaabc | Greedily place the most frequent character at alternating even indices first, then fill odd indices. |
| Maximum length constraints up to the problem limit | Use a linear time O(n) frequency array and greedy placement to scale efficiently without performance bottlenecks. |
| Cases where no valid rearrangement is possible | Ensure the max frequency check catches this scenario early and returns an empty string. |
| Multiple valid solutions exist for the same input string | Any valid placement adhering to the alternating index rule is accepted by the problem statement. |