Problem · String

Reorganize a String

Learn this problem
MediumAmazon logoAmazonINTERNONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Rearrange a lowercase string so that no two adjacent characters are equal. If no such arrangement exists, return the empty string.

To make the judged result deterministic, construct the answer with this rule: at each position, select the eligible character with the greatest remaining frequency. The previously placed character is not eligible. If several eligible characters have the same frequency, select the lexicographically smallest one.

Function

reorganizeString(s: String) → String

Examples

Example 1

s = "aab"return = "aba"

The highest-frequency eligible character is chosen first, producing a valid arrangement.

Example 2

s = "aaab"return = ""

Three copies of one character cannot be separated by the single remaining character.

Example 3

s = "aabbcc"return = "abcabc"

Frequency ties are resolved in lexicographic order while the previous character remains temporarily ineligible.

Constraints

  • 1 <= s.length <= 10^5
  • s contains only lowercase English letters.

More Amazon problems

drafts saved locally
public String reorganizeString(String s) {
    // Write your solution here.
}
s"aab"
expected"aba"
checking account