Skip to main content
Back to problems
#2193
Hard Algorithms

Minimum number of moves to make palindrome

Two Pointers String Greedy Binary Indexed Tree
52.6% acceptance
Feb 25, 2026
1052
78
You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters and swap them. Return the minimum number of moves needed to make s a palindrome.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_moves_to_make_palindrome(s: String) -> i32 {
    let mut chars: Vec<u8> = s.into_bytes();
    let mut moves = 0i32;
    let mut l = 0;
    let mut r = chars.len() - 1;
    while l < r {
      if chars[l] == chars[r] {
        l += 1;
        r -= 1;
      } else {
        // Find matching char for chars[l] from the right
        let mut j = r;
        while j > l && chars[j] != chars[l] {
          j -= 1;
        }
        if j == l {
          // Odd center char: move toward center
          chars.swap(l, l + 1);
          moves += 1;
        } else {
          // Move chars[j] to position r
          for i in j..r {
            chars.swap(i, i + 1);
          }
          moves += (r - j) as i32;
          l += 1;
          r -= 1;
        }
      }
    }
    moves
  }
}