Imagine you are organizing a playlist where no two songs by the same artist should play consecutively to keep the audience engaged.
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. If such an arrangement is not possible, return an empty string. Otherwise, return any valid rearrangement.
1 ≤ s.length ≤ 10^5s consists of lowercase English letters only
Edge cases: Single character string → always valid, output same characterAll characters are the same → no valid rearrangement, output empty stringString with two characters both same → no valid rearrangement, output empty string
def reorganizeString(s: str) -> str:public String reorganizeString(String s)string reorganizeString(string s)function reorganizeString(s)
def reorganizeString(s: str) -> str:
# Write your solution here
pass
class Solution {
public String reorganizeString(String s) {
// Write your solution here
return "";
}
}
#include <string>
using namespace std;
string reorganizeString(string s) {
// Write your solution here
return "";
}
function reorganizeString(s) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: aabReturning original string without rearrangement even when adjacent duplicates exist.✅ Implement frequency counting and use a max heap to rearrange characters to avoid adjacency.
Wrong: aaReturning input string when no valid rearrangement exists (e.g., all characters same).✅ Add a check for max frequency > (n+1)/2 and return empty string if true.
Wrong: aaaabcGreedy approach that does not hold back previously used character causing adjacent duplicates.✅ Use a variable to store last used character and reinsert it into heap only after placing a different character.
Wrong: abcabcabIncorrect handling of equal frequency characters leading to adjacent duplicates.✅ Always pick two different characters from heap each iteration and reinsert if counts remain.
Wrong: TLE or timeoutUsing brute force or backtracking approach with factorial complexity.✅ Implement a heap-based greedy solution with O(n log k) complexity.