Rearrange a String So Adjacent Characters Differ
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Construct the lexicographically smallest rearrangement of a lowercase string with no equal adjacent characters, checking feasibility after each deterministic choice and returning empty when separation is impossible.
Read the full Amazon Software Engineer interview experience this question came from
Constraints
- 1 <= len(s) <= 200000.
- The input contains only lowercase English letters.
- Every input character must appear exactly once in a nonempty result.
- Return an empty string only when no arrangement can avoid equal adjacent characters.
- Among valid arrangements, return the lexicographically smallest one.
Examples
Input: ('aab',)
Expected Output: 'aba'
Explanation: This source example has one feasible arrangement, which is therefore lexicographically smallest.
Input: ('aaab',)
Expected Output: ''
Explanation: Three copies of a cannot be separated by the one other character.
Hints
- First compare the largest frequency with the number of separator positions available.
- At each position, try letters in order but reject a choice if the remaining dominant count can no longer be separated, including from the letter just chosen.