#767 Reorganize String
frequently reported atAmazonByteDance / TikTokOracleGoogleMicrosoftSalesforce
the problem
In plain words
Rearrange the characters of s so no two adjacent characters are equal. Return any valid result, or "" if impossible.
in s = "aab"
out "aba"
in s = "aaab"
out ""
- 1 ≤ s.length ≤ 500
- Lowercase English letters
your turn
Try it before you peek
Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.
Solve it in the browser
LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.
Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.
Marking the problem solved, or opening every hint, also shows it.
the aha
Key insight
patternGreedy with a heapFrequency counting
It's possible iff the most frequent letter appears at most ⌈n/2⌉ times. Greedily place the letter with the most copies left, but never the one you just placed.
solutions
From brute force to optimal
Always append the most frequent available letter; the just-used letter sits out one turn.
- Count; max-heap of letters by count.
- Poll c, append, decrement; then re-offer the previously held letter.
- If the heap empties early, return "".
n steps on a heap of ≤ 26 letters: O(n log 26).
26 counts (plus the output).
class Solution { public String reorganizeString(String s) { int[] count = new int[26]; for (char c : s.toCharArray()) count[c - 'a']++; // max-heap of letters by remaining count PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> Integer.compare(count[b], count[a])); for (int c = 0; c < 26; c++) if (count[c] > 0) heap.offer(c); StringBuilder sb = new StringBuilder(); int held = -1; // letter we just used: must sit out one turn while (!heap.isEmpty()) { int c = heap.poll(); // most frequent letter that isn't the last one sb.append((char) ('a' + c)); count[c]--; if (held >= 0 && count[held] > 0) heap.offer(held); // previous letter may come back now held = c; } return sb.length() == s.length() ? sb.toString() : ""; // stuck with only `held` left → impossible }}Put the most frequent letter at 0, 2, 4…, then the rest continue on even slots and wrap to odd ones.
- If maxCount > (n + 1) / 2 → "".
- Write the most frequent letter at even indices.
- Write the others, switching to index 1 when evens run out.
One counting pass and one writing pass.
26 counts (plus the output array).
class Solution { public String reorganizeString(String s) { int n = s.length(); int[] count = new int[26]; int top = 0; for (char c : s.toCharArray()) if (++count[c - 'a'] > count[top]) top = c - 'a'; if (count[top] > (n + 1) / 2) return ""; // too many of one letter: impossible char[] out = new char[n]; int i = 0; for (; count[top] > 0; count[top]--, i += 2) out[i] = (char) ('a' + top); // most frequent first for (int c = 0; c < 26; c++) { for (; count[c] > 0; count[c]--, i += 2) { if (i >= n) i = 1; // even slots full → switch to odd slots out[i] = (char) ('a' + c); } } return new String(out); }}in the room
How to say it in the interview
talk track
- State the impossibility condition first — it shows you understand the structure.
traps
- Using
n / 2as the limit instead of(n + 1) / 2: "aab" (n = 3, two a's) would be wrongly rejected. - Even slots: not writing the most frequent letter first. For "aaabb", writing b first gives "babaa".
- Heap: offering the letter you just used straight back, so it can be picked twice in a row.
what they ask next
Follow-ups
Rearrange String k Distance Apart (LC 358)?
Same heap, but letters wait in a queue for k turns before returning to the heap.
before you submit
Edge cases to test
- One letter: return it as is.
- "aa" → "": two equal letters can never be separated.
- Max count exactly (n + 1) / 2 is still possible: "aab" → "aba".
practise next
Similar problems
- #621Task SchedulerMediumin Heaps
- #1046Last Stone WeightEasyin Heaps