Fewest Neighbor Swaps to Mirror a Word
StringsAuto-graded · 22 test casesLast 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
0moves. - 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
-1when it is impossible.
Constraints
1 <= len(word) <= 2000wordcontains only lowercase English letters (atoz).
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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Feasibility. A palindrome pairs up letters symmetrically around the center, so at most one letter may have an odd count (and it sits in the middle). If two or more letters have odd counts, return -1.
Counting swaps greedily. Keep two pointers, left and right, and fix the outer positions first, moving inward:
- If
chars[left] == chars[right], that outer pair is done; move both pointers inward. - Otherwise, scan from
rightleftward for the nearest copy ofchars[left], at indexmatch.- If
match > left, bubble it torightwith adjacent swaps (costright - match), then move both pointers inward. - If
match == left, the letter atlefthas no partner, so it is the odd letter. Swap it one step to the right (cost 1) and keep the pointers where they are. The next iteration pairs a different letter atleft. The odd letter is thus pushed inward only as far as needed and ends up in the middle.
- If
Why it is correct
- Pairing the leftmost letter with the nearest copy from the right is optimal by an exchange argument: equal letters never need to cross each other, so the leftmost copy of a letter pairs with its rightmost copy, and choosing the closest one minimizes the bubbling distance without disturbing the relative order of the other letters.
- Deferring the odd letter is equivalent to placing it in the center last. Sending it to the center immediately would force every later pair to cross it, adding unnecessary swaps. Moving it one step at a time only charges for characters that truly lie between it and the center.
- After each pair is fixed, the remaining problem is an independent instance on the inner substring, so the local choices combine into a global optimum.
Complexity
- Time: O(n²). Each of about n/2 rounds does an O(n) scan and O(n) bubbling; the odd-letter nudges add at most O(n) further steps.
- Space: O(n) for the character list and the counter.
Reference solution
from collections import Counter
def min_adjacent_swaps_palindrome(word: str) -> int:
# A palindrome allows at most one letter with an odd count.
if sum(c % 2 for c in Counter(word).values()) > 1:
return -1
chars = list(word)
left = 0
right = len(chars) - 1
swaps = 0
while left < right:
if chars[left] == chars[right]:
left += 1
right -= 1
continue
# Closest copy of chars[left], searching from the right end.
match = right
while match > left and chars[match] != chars[left]:
match -= 1
if match == left:
# chars[left] is the odd letter: nudge it one step inward.
chars[left], chars[left + 1] = chars[left + 1], chars[left]
swaps += 1
else:
# Bubble the partner to the right end.
while match < right:
chars[match], chars[match + 1] = chars[match + 1], chars[match]
match += 1
swaps += 1
left += 1
right -= 1
return swaps