767. Reorganize String
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 <= 500
- s consists of lowercase English letters.
From: LeetCode
Link: 767. Reorganize String
Solution:
Ideas:
1. Frequency Counting: First, I count how many times each character appears in the input string.
2. Possibility Check: Before attempting to reorganize, I check if it’s even possible. If any character appears more than (len + 1) / 2 times, it’s impossible to arrange them without having adjacent duplicates.
3. Greedy Selection: For each position in the result string, I select the character with the highest remaining frequency that is different from the previously placed character.
4. Character Placement: I place the selected character and decrement its frequency count.
Code:
char* reorganizeString(char* s) {
int len = strlen(s);
// Count frequency of each character
int freq[26] = {0};
for (int i = 0; i < len; i++) {
freq[s[i] - 'a']++;
}
// Check if reorganization is possible
// If any character appears more than (len + 1) / 2 times, it's impossible
int maxFreq = 0;
for (int i = 0; i < 26; i++) {
if (freq[i] > maxFreq) {
maxFreq = freq[i];
}
}
if (maxFreq > (len + 1) / 2) {
return "";
}
// Create result string
char* result = (char*)malloc((len + 1) * sizeof(char));
result[len] = '\0';
// Use a simple approach: always pick the most frequent character
// that is different from the previous character
int pos = 0;
while (pos < len) {
int maxIdx = -1;
int maxCount = 0;
// Find the character with maximum frequency that's different from previous
for (int i = 0; i < 26; i++) {
if (freq[i] > maxCount) {
// Check if this character is different from the previous one
if (pos == 0 || (char)('a' + i) != result[pos - 1]) {
maxCount = freq[i];
maxIdx = i;
}
}
}
// If we can't find a suitable character, try the second most frequent
if (maxIdx == -1) {
// This shouldn't happen if our initial check was correct
free(result);
return "";
}
// Place the character and decrease its frequency
result[pos] = 'a' + maxIdx;
freq[maxIdx]--;
pos++;
}
return result;
}