Ctrl K

No Letter Facing Its Twin

Hard
You are given a string letters of even length n made of lowercase English letters. Its positions split into mirrored pairs: position i faces position n - 1 - i. Rearrange the letters (swapping any two letters as many times as you like) so that no mirrored pair holds the same letter twice. Among all arrangements that work, return the smallest one in dictionary order. If no such arrangement exists, return the string "-1".
Example 1
letters="zaza" → 'aazz'

In aazz the mirrored pairs are (a, z) and (a, z), so nothing matches. No smaller string can be made from these letters.

Example 2
letters="cbbaba" → 'aabcbb'

The sorted string aabbbc fails because the two middle letters are both b. Rearranging the right half into cbb gives aabcbb with pairs (a, b), (a, b), (b, c).

Example 3
letters="kkkkkm" → '-1'

There are three pairs but five k letters, so some pair must get two k. The answer is "-1".

Constraints
  • 2 ≤ len(letters) ≤ 10⁵
  • the length of letters is even
  • letters consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEqual Letters Kept Apart HardDistinct Word Shorthands HardSorting Piece by Piece HardBiggest Number From Pieces MediumStrength of the Weaker Partner Easy
loading Python…
Input
letters="zaza"
Expected
'aazz'

Run checks the first 3 tests in your browser. Submit checks all 44 tests on the server, hidden ones included.