KatInterview

Fewest Neighbor Swaps to Mirror a Word

StringsAuto-graded · 22 test cases
HardAuto-gradedStringsgreedytwo-pointersstrings

Last updated

Compute the minimum number of adjacent character swaps needed to rearrange a lowercase string into a palindrome, or report -1 if no palindrome is possible.

Fewest Neighbor Swaps to Mirror a Word

You are given a string word made of lowercase English letters. In one move you may pick two neighboring positions and exchange the letters stored there.

Find the smallest number of such moves that turns word into a palindrome (a string that reads the same forwards and backwards). Any palindrome may be the target; you are free to pick whichever one is cheapest to reach.

If no rearrangement of the letters can ever form a palindrome, return -1.

Details

  • A string that is already a palindrome (including a single character) needs 0 moves.
  • Only swaps of two adjacent positions count as moves; each one costs exactly 1.
  • The function returns a single integer: the minimum move count, or -1 when it is impossible.

Constraints

  • 1 <= len(word) <= 2000
  • word contains only lowercase English letters (a to z).

Examples

Example 1

Input: min_adjacent_swaps_palindrome('aabb')

Output: 2

Example 2

Input: min_adjacent_swaps_palindrome('ntiin')

Output: 1

Hints

Hint 1

First decide feasibility from letter counts alone: how many letters may appear an odd number of times in a palindrome?

Hint 2

Work from both ends inward. Look at the leftmost letter and find its partner among the remaining letters; think about which copy of that letter is cheapest to bring to the opposite end.

Hint 3

Equal letters never need to pass each other. If the leftmost letter has no partner, it must be the odd-count letter that belongs in the middle; move it one step inward and handle the next letter, rather than sending it to the center immediately.