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 makesa palindrome.
Note that the input will be generated such that s can always be converted to a palindrome.
Example 1:
Input: s = "aabb"
Output: 2
Explanation:
We can obtain two palindromes from s, "abba" and "baab".
- We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba".
- We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab".
Thus, the minimum number of moves needed to make s a palindrome is 2.
Example 2:
Input: s = "letelt"
Output: 2
Explanation:
One of the palindromes we can obtain from s in 2 moves is "lettel".
One of the ways we can obtain it is "letelt" -> "letetl" -> "lettel".
Other palindromes such as "tleelt" can also be obtained in 2 moves.
It can be shown that it is not possible to obtain a palindrome in less than 2 moves.
Constraints:
1 <= s.length <= 2000
s consists only of lowercase English letters.
s can be converted to a palindrome using a finite number of moves.
Problem summary: 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 that the input will be generated such that s can always be converted to a palindrome.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers · Greedy · Segment Tree
Example 1
"aabb"
Example 2
"letelt"
Related Problems
Minimum Insertion Steps to Make a String Palindrome (minimum-insertion-steps-to-make-a-string-palindrome)
Minimum Number of Flips to Make Binary Grid Palindromic I (minimum-number-of-flips-to-make-binary-grid-palindromic-i)
Step 02
Core Insight
What unlocks the optimal approach
Consider a greedy strategy.
Let’s start by making the leftmost and rightmost characters match with some number of swaps.
If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2193: Minimum Number of Moves to Make Palindrome
class Solution {
public int minMovesToMakePalindrome(String s) {
int n = s.length();
int ans = 0;
char[] cs = s.toCharArray();
for (int i = 0, j = n - 1; i < j; ++i) {
boolean even = false;
for (int k = j; k != i; --k) {
if (cs[i] == cs[k]) {
even = true;
for (; k < j; ++k) {
char t = cs[k];
cs[k] = cs[k + 1];
cs[k + 1] = t;
++ans;
}
--j;
break;
}
}
if (!even) {
ans += n / 2 - i;
}
}
return ans;
}
}
// Accepted solution for LeetCode #2193: Minimum Number of Moves to Make Palindrome
func minMovesToMakePalindrome(s string) int {
cs := []byte(s)
ans, n := 0, len(s)
for i, j := 0, n-1; i < j; i++ {
even := false
for k := j; k != i; k-- {
if cs[i] == cs[k] {
even = true
for ; k < j; k++ {
cs[k], cs[k+1] = cs[k+1], cs[k]
ans++
}
j--
break
}
}
if !even {
ans += n/2 - i
}
}
return ans
}
# Accepted solution for LeetCode #2193: Minimum Number of Moves to Make Palindrome
class Solution:
def minMovesToMakePalindrome(self, s: str) -> int:
cs = list(s)
ans, n = 0, len(s)
i, j = 0, n - 1
while i < j:
even = False
for k in range(j, i, -1):
if cs[i] == cs[k]:
even = True
while k < j:
cs[k], cs[k + 1] = cs[k + 1], cs[k]
k += 1
ans += 1
j -= 1
break
if not even:
ans += n // 2 - i
i += 1
return ans
// Accepted solution for LeetCode #2193: Minimum Number of Moves to Make Palindrome
/**
* [2193] Minimum Number of Moves to Make Palindrome
*
* 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 that the input will be generated such that s can always be converted to a palindrome.
*
* Example 1:
*
* Input: s = "aabb"
* Output: 2
* Explanation:
* We can obtain two palindromes from s, "abba" and "baab".
* - We can obtain "abba" from s in 2 moves: "a<u>ab</u>b" -> "ab<u>ab</u>" -> "abba".
* - We can obtain "baab" from s in 2 moves: "a<u>ab</u>b" -> "<u>ab</u>ab" -> "baab".
* Thus, the minimum number of moves needed to make s a palindrome is 2.
*
* Example 2:
*
* Input: s = "letelt"
* Output: 2
* Explanation:
* One of the palindromes we can obtain from s in 2 moves is "lettel".
* One of the ways we can obtain it is "lete<u>lt</u>" -> "let<u>et</u>l" -> "lettel".
* Other palindromes such as "tleelt" can also be obtained in 2 moves.
* It can be shown that it is not possible to obtain a palindrome in less than 2 moves.
*
*
* Constraints:
*
* 1 <= s.length <= 2000
* s consists only of lowercase English letters.
* s can be converted to a palindrome using a finite number of moves.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/
// discuss: https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn min_moves_to_make_palindrome(s: String) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2193_example_1() {
let s = "aabb".to_string();
let result = 2;
assert_eq!(Solution::min_moves_to_make_palindrome(s), result);
}
#[test]
#[ignore]
fn test_2193_example_2() {
let s = "letelt".to_string();
let result = 2;
assert_eq!(Solution::min_moves_to_make_palindrome(s), result);
}
}
// Accepted solution for LeetCode #2193: Minimum Number of Moves to Make Palindrome
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2193: Minimum Number of Moves to Make Palindrome
// class Solution {
// public int minMovesToMakePalindrome(String s) {
// int n = s.length();
// int ans = 0;
// char[] cs = s.toCharArray();
// for (int i = 0, j = n - 1; i < j; ++i) {
// boolean even = false;
// for (int k = j; k != i; --k) {
// if (cs[i] == cs[k]) {
// even = true;
// for (; k < j; ++k) {
// char t = cs[k];
// cs[k] = cs[k + 1];
// cs[k + 1] = t;
// ++ans;
// }
// --j;
// break;
// }
// }
// if (!even) {
// ans += n / 2 - i;
// }
// }
// return ans;
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(1)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.