InferenceAI

Enter at least two characters to search.

Start free

Reorganise Letters

mediumHeaps25 min25 XP

Rearrange s so no two adjacent characters are the same, and return the result. Use this deterministic rule so the answer is unique: at each step, place the most frequent remaining character that differs from the last one placed (ties broken alphabetically). Return "" if it's impossible.

Examples

EXAMPLE WALKTHROUGHpossible

A guided view of the published example, not a trace of your code.

INPUT["aab"]
TASKreorganise_letters()
EXPECTED OUTPUT"aba"

Start with the input values shown in this example.

Example 1 of 3

Input: s = "aab"

Output: "aba"

Explanation: possible

Input: s = "aaab"

Output: ""

Explanation: impossible

Input: s = "a"

Output: "a"

Explanation: single

Hint 1

A max-heap keyed by (-count, char) gives the most frequent character; hold back the last-used one for a step.

Topics

DSAHeapsPython