FastPrepRearrange a String So Adjacent Characters Differ

Rearrange a String So Adjacent Characters Differ

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Rearrange all characters of s so no two adjacent characters are equal.

Return the lexicographically smallest valid rearrangement. Return the empty string when no valid rearrangement exists. Character comparisons use ASCII order.

Function

rearrangeWithoutAdjacentEquals(s: String) → String

Examples

Example 1

s = "aab"return = "aba"

aba is valid and is the only arrangement without equal neighbors.

Example 2

s = "aaab"return = ""

Three copies of a cannot be separated by one b.

Example 3

s = "aabbcc"return = "abacbc"

This is the lexicographically smallest valid use of all characters.

Constraints

  • 0 <= s.length <= 2000.
  • s contains ASCII letters.

More Google problems

See Google hiring insights
public String rearrangeWithoutAdjacentEquals(String s) {
    // Write your code here.
}
s"aab"
expected"aba"
Checking account…