Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Greedy
"aab"
"aaab"
rearrange-string-k-distance-apart)task-scheduler)longest-happy-string)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #767: Reorganize String
class Solution {
public String reorganizeString(String s) {
int[] cnt = new int[26];
int mx = 0;
for (char c : s.toCharArray()) {
int t = c - 'a';
++cnt[t];
mx = Math.max(mx, cnt[t]);
}
int n = s.length();
if (mx > (n + 1) / 2) {
return "";
}
int k = 0;
for (int v : cnt) {
if (v > 0) {
++k;
}
}
int[][] m = new int[k][2];
k = 0;
for (int i = 0; i < 26; ++i) {
if (cnt[i] > 0) {
m[k++] = new int[] {cnt[i], i};
}
}
Arrays.sort(m, (a, b) -> b[0] - a[0]);
k = 0;
StringBuilder ans = new StringBuilder(s);
for (int[] e : m) {
int v = e[0], i = e[1];
while (v-- > 0) {
ans.setCharAt(k, (char) ('a' + i));
k += 2;
if (k >= n) {
k = 1;
}
}
}
return ans.toString();
}
}
// Accepted solution for LeetCode #767: Reorganize String
func reorganizeString(s string) string {
cnt := make([]int, 26)
for _, c := range s {
t := c - 'a'
cnt[t]++
}
mx := slices.Max(cnt)
n := len(s)
if mx > (n+1)/2 {
return ""
}
m := [][]int{}
for i, v := range cnt {
if v > 0 {
m = append(m, []int{v, i})
}
}
sort.Slice(m, func(i, j int) bool {
return m[i][0] > m[j][0]
})
ans := make([]byte, n)
k := 0
for _, e := range m {
v, i := e[0], e[1]
for v > 0 {
ans[k] = byte('a' + i)
k += 2
if k >= n {
k = 1
}
v--
}
}
return string(ans)
}
# Accepted solution for LeetCode #767: Reorganize String
class Solution:
def reorganizeString(self, s: str) -> str:
n = len(s)
cnt = Counter(s)
mx = max(cnt.values())
if mx > (n + 1) // 2:
return ''
i = 0
ans = [None] * n
for k, v in cnt.most_common():
while v:
ans[i] = k
v -= 1
i += 2
if i >= n:
i = 1
return ''.join(ans)
// Accepted solution for LeetCode #767: Reorganize String
use std::collections::{BinaryHeap, HashMap, VecDeque};
impl Solution {
#[allow(dead_code)]
pub fn reorganize_string(s: String) -> String {
let mut map = HashMap::new();
let mut pq = BinaryHeap::new();
let mut ret = String::new();
let mut queue = VecDeque::new();
let n = s.len();
// Initialize the HashMap
for c in s.chars() {
map.entry(c)
.and_modify(|e| {
*e += 1;
})
.or_insert(1);
}
// Initialize the binary heap
for (k, v) in map.iter() {
if 2 * *v - 1 > n {
return "".to_string();
} else {
pq.push((*v, *k));
}
}
while !pq.is_empty() {
let (v, k) = pq.pop().unwrap();
ret.push(k);
queue.push_back((v - 1, k));
if queue.len() == 2 {
let (v, k) = queue.pop_front().unwrap();
if v != 0 {
pq.push((v, k));
}
}
}
if ret.len() == n {
ret
} else {
"".to_string()
}
}
}
// Accepted solution for LeetCode #767: Reorganize String
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #767: Reorganize String
// class Solution {
// public String reorganizeString(String s) {
// int[] cnt = new int[26];
// int mx = 0;
// for (char c : s.toCharArray()) {
// int t = c - 'a';
// ++cnt[t];
// mx = Math.max(mx, cnt[t]);
// }
// int n = s.length();
// if (mx > (n + 1) / 2) {
// return "";
// }
// int k = 0;
// for (int v : cnt) {
// if (v > 0) {
// ++k;
// }
// }
// int[][] m = new int[k][2];
// k = 0;
// for (int i = 0; i < 26; ++i) {
// if (cnt[i] > 0) {
// m[k++] = new int[] {cnt[i], i};
// }
// }
// Arrays.sort(m, (a, b) -> b[0] - a[0]);
// k = 0;
// StringBuilder ans = new StringBuilder(s);
// for (int[] e : m) {
// int v = e[0], i = e[1];
// while (v-- > 0) {
// ans.setCharAt(k, (char) ('a' + i));
// k += 2;
// if (k >= n) {
// k = 1;
// }
// }
// }
// return ans.toString();
// }
// }
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.