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 INPUT String s = "aab" a idx 0 a idx 1 b idx 2 Character Count: 'a': 2 'b': 1 Length: 3 (odd) Odd char: 'b' (center) Goal: Make palindrome "aba" or "aba" ALGORITHM STEPS 1 Count Characters Track frequency of each char 2 Two Pointer Greedy Match chars from both ends 3 Find Matching Char Search for pair to swap 4 Count Swaps Sum adjacent swaps needed Swap Process: Before: a a b swap After: a b a FINAL RESULT Palindrome Achieved: a b a mirrors OK Output: 1 Only 1 swap needed: "aab" --> "aba" Verified: OK Key Insight: The greedy approach works by matching characters from both ends. For each position, find the matching character closest to its target position and count the adjacent swaps needed. Characters with odd frequency must go to the center. Time: O(n^2), Space: O(n) for character tracking. TutorialsPoint - Minimum Number of Moves to Make Palindrome | Optimized Greedy with Character Counting
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