oneby7

Heaps Simulating with a heap

418. Reorganize String

Medium

You are given a string s. Rearrange its letters so that no two neighbouring characters are the same, and return the new string. It must use every letter of s exactly as many times as s does.

Sometimes no such string exists. Then return the empty string "". Answers are shown in double quotes.

Many strings can be right, and any of them is a correct answer. The result shows a valid arrangement when yours is one, and correctly impossible when you return "" and no arrangement exists. Otherwise it names the first thing wrong, such as positions 4 and 5 are both 'a' or the letters changed: one 'b' is missing. Positions count from 0.

Example 1

Input: s = "aaabbc"

Output: "ababac"

Explanation: No two neighbours are the same, and the string still has three a, two b and one c. "abacab" and "acabab" are also correct.

Example 2

Input: s = "aab"

Output: "aba"

Explanation: a appears twice in three letters, so it has to take the first and the last position, with b between them.

Example 3

Input: s = "zzzy"

Output: ""

Explanation: Three z need two other letters to keep them apart, and there is only one y. Every order puts two z side by side, so the answer is the empty string.

Check your understanding

Work out the answer for this input before you write any code.

s = "aabbb"

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds only the lowercase letters a to z.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.