Reorganize String

MediumHashing · Greedy · Counting🧩 Hashing & CountingLeetCode #767 ↗Updated

Problem

Rearrange the letters of the lowercase string s so that no two neighbouring characters are equal. Return any arrangement that works, or the empty string "" if no such arrangement exists.
Inputs = "aab"Output"aba"
Inputs = "aaab"Output""
Inputs = "aaabbc"Output"ababac" (any valid answer accepted)

1 ≤ s.length ≤ 500  ·  s consists of lowercase English letters

Try it yourself

Java
class Solution {
    public String reorganizeString(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Only the most frequent letter can cause trouble. It fits iff its count is at most ⌈n/2⌉; then dropping it on indices 0, 2, 4, … and filling the remaining slots with the other letters (evens first, then odds) never puts two equal letters side by side.
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceBacktracking over Letter Counts

Time O(kn)Space O(n)

Build the answer position by position. At each position try every letter that still has copies left and differs from the previous letter; recurse, and undo the choice if the rest cannot be completed. k = distinct letters (≤ 26).

Java
public String reorganizeString(String s) {
    int[] left = new int[26];
    for (char c : s.toCharArray()) left[c - 'a']++;
    char[] out = new char[s.length()];
    return place(left, out, 0) ? new String(out) : "";
}

private boolean place(int[] left, char[] out, int pos) {
    if (pos == out.length) return true;
    for (int c = 0; c < 26; c++) {
        if (left[c] == 0 || (pos > 0 && out[pos - 1] == 'a' + c)) continue;
        left[c]--;
        out[pos] = (char) ('a' + c);
        if (place(left, out, pos + 1)) return true;
        left[c]++; // undo and try the next letter
    }
    return false;
}

Explores the arrangement space blindly — exponential on bad inputs.

At a glance

LevelApproachTimeSpace
Brute ForceBacktracking over Letter CountsO(kn)O(n)
BetterMax-Heap Greedy with Cool-DownO(n log k)O(k)
OptimalEven-Then-Odd Slot FillingO(n)O(1)
Common pitfalls
  • Using n/2 instead of (n+1)/2 — rejects valid odd-length inputs like "aba".
  • Popping the top two from a heap at once without a cool-down — ties can produce "abba".
  • Filling odd slots before the dominant letter has taken its evens.
Interview tips
  • State the feasibility condition first: max count ≤ ⌈n/2⌉.
  • Ask whether any valid answer is accepted — it is, so greedy is fine.
  • Mention the heap version extends to Rearrange String k Distance Apart.
Pattern
Greedy on the most frequent item → arrange items so equal ones are separated; the largest group decides feasibility.
My notes saved in this browser