Reorganize String solution explained

Reorganize String asks you to rearrange the letters of a string so that no two neighbors are equal, or return an empty string if that cannot be done. It is possible exactly when the most frequent letter appears at most ceil(n / 2) times. To build an answer, write the most frequent letter into positions 0, 2, 4 and onward, then continue with the remaining letters through the even positions and wrap around to the odd ones. Counting and placing take O(n) time with O(1) extra memory for a fixed alphabet.

By Published 8 min read

The problem, restated

You get a string of lowercase letters. Rearrange its letters, using each exactly as often as it appears, so that no letter sits directly next to the same letter. Return any arrangement that works. If no arrangement works, return the empty string.

Examples written for this page
InputA valid outputNote
"aabc""abac"a appears twice out of four, which is allowed
"vvvlo""vlvov"v appears three times out of five, exactly the limit
"aaab"""a appears three times out of four, one too many
"zz"""Two equal letters can never be separated
""""The empty string is already valid
Examples written for this page. Scroll sideways on a small screen.

What the interviewer is testing

There are two skills here. The first is finding the exact condition for impossibility and being able to argue it: the most frequent letter needs a different letter between each pair of its copies. The second is constructing an answer greedily without backtracking. Interviewers accept either the heap approach or the even-index placement, but they will ask why your construction never puts two equal letters together, so be ready with the argument, not just the code.

Follow-ups

  • Equal letters must be at least k apart. The heap approach generalizes: hold each used letter in a waiting queue for k - 1 steps before it can return.
  • Return the number of valid arrangements. A different, much harder counting problem; say so rather than guessing.
  • Lexicographically smallest valid arrangement. Greedy by smallest letter with a feasibility check on the remainder at each step.
  • Task scheduling with a cooldown. The same counting bound decides how many idle slots are needed.

Why the bound is exact

Suppose letter x appears m times in a string of length n. Between consecutive copies of x there must be at least one other letter, so the string needs at least m + (m - 1) = 2m - 1 positions. That gives 2m - 1 <= n, which is the same as m <= (n + 1) // 2. If that holds for the most frequent letter, it holds for all of them, and the construction below always succeeds. So the bound is both necessary and sufficient.

Brute force

Try every distinct permutation and return the first one with no equal neighbors. For n letters that is up to n! orderings, which is only useful for checking small cases. It is still worth mentioning, because it shows you know what "correct" means before optimizing.

from itertools import permutations

def reorganize_slow(s):
    for p in set(permutations(s)):
        if all(p[i] != p[i + 1] for i in range(len(p) - 1)):
            return "".join(p)
    return ""
Python: search permutations, for tiny inputs only.

Placement on even, then odd, positions

Count the letters. If the top count exceeds (n + 1) // 2, return "". Otherwise lay the letters into an array: start at index 0 and step by 2, writing every copy of the most frequent letter first. Then write the copies of the other letters in any order, continuing the same walk. When the index runs past the end, jump to index 1 and keep stepping by 2.

Why are neighbors never equal? Two adjacent positions are one even and one odd. A letter's copies are written at consecutive steps of the walk, so the only way one letter can land on both an even and an odd position is to wrap from the end of the evens to the start of the odds. The most frequent letter goes first, so it starts at index 0 and fits within the evens without wrapping. Any other letter that wraps occupies a few of the last even positions and a few of the first odd ones, and since it has no more copies than the most frequent letter, which already filled the even positions before it, those two groups can never touch.

from collections import Counter

def reorganize(s):
    n = len(s)
    counts = Counter(s)
    if not counts:
        return ""
    top, top_count = counts.most_common(1)[0]
    if top_count > (n + 1) // 2:
        return ""
    out = [""] * n
    i = 0
    order = [top] + [c for c in counts if c != top]
    for c in order:
        for _ in range(counts[c]):
            if i >= n:
                i = 1
            out[i] = c
            i += 2
    return "".join(out)
Python: count, check the bound, fill evens then odds.
function reorganizeString(s) {
  const n = s.length;
  const counts = new Map();
  for (const ch of s) counts.set(ch, (counts.get(ch) || 0) + 1);
  let top = "";
  let topCount = 0;
  for (const [ch, c] of counts) {
    if (c > topCount) {
      top = ch;
      topCount = c;
    }
  }
  if (topCount > Math.floor((n + 1) / 2)) return "";
  const out = new Array(n);
  let i = 0;
  const order = [top, ...Array.from(counts.keys()).filter((ch) => ch !== top)];
  for (const ch of order) {
    for (let k = 0; k < (counts.get(ch) || 0); k++) {
      if (i >= n) i = 1;
      out[i] = ch;
      i += 2;
    }
  }
  return out.join("");
}
JavaScript: the same placement.

Trace "vvvlo": n = 5, v appears 3 times and (5 + 1) // 2 = 3, so it is possible. v goes to 0, 2 and 4. The index is now 6, past the end, so l goes to 1 and o to 3. The result is "vlvov". For "aaab", a appears 3 times but the limit is (4 + 1) // 2 = 2, so the answer is "".

Heap alternative

Another greedy builds the string left to right: always append the most frequent remaining letter that differs from the last letter written. A max-heap of (count, letter) gives that in O(log a) per step. Hold back the letter you just used for one step, then push it again if copies remain. If the heap is empty while a held letter still has copies, no valid arrangement exists.

import heapq
from collections import Counter

def reorganize_heap(s):
    heap = [(-count, ch) for ch, count in Counter(s).items()]
    heapq.heapify(heap)
    out = []
    held = None  # (negative count, letter) used in the previous step
    while heap:
        count, ch = heapq.heappop(heap)
        out.append(ch)
        if held:
            heapq.heappush(heap, held)
        held = (count + 1, ch) if count + 1 < 0 else None
    return "".join(out) if held is None else ""
Python: max-heap with a one-step hold.

Complexity

n letters, a distinct letters
ApproachTimeExtra memory
All permutationsO(n! · n)O(n! · n) for the set of permutations
Even, then odd placementO(n + a)O(a) for counts, plus the output
Max-heap with a holdO(n log a)O(a), plus the output
n letters, a distinct letters. Scroll sideways on a small screen.

With a fixed alphabet of 26 letters, a is a constant and both greedy approaches are linear in practice.

Edge cases

  • Empty string or one letter: return it unchanged.
  • A count exactly at the limit, such as "vvvlo", which must succeed.
  • A count one over the limit, such as "aaab", which must fail.
  • Two letters with equal top counts, like "aabb", where either can go first.
  • Odd and even lengths, which change the limit: (n + 1) // 2 is 3 for n = 5 and 2 for n = 4.

Common mistakes

  • Using n // 2 as the limit, which wrongly rejects inputs like "aab" whose answer is "aba".
  • Placing letters in alphabetical order on evens without putting the most frequent letter first, which can create adjacent duplicates when a frequent letter wraps.
  • In the heap version, pushing the used letter back immediately, so it can be chosen again next step.
  • Forgetting to check for leftover copies when the heap empties, and returning a too-short string.
  • Returning None or null instead of the empty string the problem asks for.

How to explain it out loud

Fictional example

Bound first, then construction
Candidate
The most frequent letter needs another letter between each pair of its copies, so with m copies I need at least 2m minus 1 slots. That means m can be at most n plus 1 over 2, rounded down. If it is larger, I return the empty string.
Candidate
If it fits, I write that letter on indexes 0, 2, 4 and so on, then keep going with the other letters, wrapping to index 1 when I run off the end. Equal letters only meet if one letter wraps far enough to touch itself, and the bound rules that out.
Candidate
Counting and placing are both linear. If you prefer, I can show the heap version, which picks the most frequent letter that is not the previous one at each step.

Top K Frequent Words is the counting-plus-heap pattern without the placement step. Maximum Frequency Stack keeps letters grouped by count so the most frequent one is always at hand, the same need the heap fills here. Valid Parentheses is another short string problem where the invariant matters more than the code.

Practicing with Natively

The argument for why the placement works is the part interviewers probe, so rehearse it in your own words. On Mac or Windows, Natively can read the problem from a screenshot in a practice session and suggest an approach once you have tried your own, and the transcript of the mock interview shows whether your proof sounded convincing or rushed. More on the AI interview assistant.

Questions people ask

How do you solve Reorganize String?

Count the letters. If the most frequent appears more than (n + 1) // 2 times, return an empty string. Otherwise place it on indexes 0, 2, 4 and onward, then the other letters, wrapping to odd indexes.

When is Reorganize String impossible?

Exactly when one letter appears more than (n + 1) // 2 times, because m copies need at least 2m - 1 positions to keep them apart.

Can I use a heap for Reorganize String?

Yes. Repeatedly take the most frequent letter that differs from the previous one, holding the used letter out for one step. It runs in O(n log a) for a distinct letters.

What is the time complexity?

O(n) for counting and placement with a fixed alphabet, and O(n log a) for the heap version.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP