Minimum Number of Moves to Make Palindrome - Problem

You are given a string s consisting only of lowercase English letters.

In one move, you can select any two adjacent characters of s and swap them.

Return the minimum number of moves needed to make s a palindrome.

Note: The input will be generated such that s can always be converted to a palindrome.

Input & Output

Example 1 — Basic Case
$ Input: s = "aab"
Output: 1
💡 Note: We can swap the second 'a' with 'b' to get 'aba', which is a palindrome. Only 1 adjacent swap is needed.
Example 2 — Already Palindrome
$ Input: s = "aba"
Output: 0
💡 Note: The string is already a palindrome, so no moves are needed.
Example 3 — Multiple Swaps
$ Input: s = "letelt"
Output: 2
💡 Note: We need 2 swaps to transform 'letelt' to a palindrome like 'tleelt'. Match 'l' at ends first, then match 'e' at next positions.

Constraints

  • 1 ≤ s.length ≤ 2000
  • s consists only of lowercase English letters
  • s can be rearranged to form a palindrome

Visualization

Tap to expand
Minimum Moves to Make Palindrome: Adjacent Swaps OnlyInput: 'aab'aabAfter 1 swap: 'aba'abaswapPalindrome Check:✓ 'aba' reads same forwards/backwardsResult: 1 moveOnly adjacent swaps allowed - find minimum sequence
Understanding the Visualization
1
Input
String 'aab' that needs to become palindrome
2
Process
Use adjacent swaps to rearrange characters
3
Output
Minimum number of swaps needed: 1
Key Takeaway
🎯 Key Insight: Use greedy two-pointer approach to match characters from ends, bubbling nearest matches with adjacent swaps
Asked in
Google 28 Facebook 15 Amazon 12
23.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen