Minimum Number of Moves to Make Palindrome

hard two pointers greedy string

Problem

You are given a string s of lowercase letters. In one move you may swap any two adjacent characters. Return the minimum number of moves needed to make s a palindrome. The input is guaranteed to be rearrangeable into a palindrome.

Inputs = "aabb"
Output2
"aabb" → "abab" → "abba": two adjacent swaps reach a palindrome.
Inputs = "letelt"
Output2
One reachable palindrome is "lettel"; it cannot be done in fewer than 2 moves.

def min_moves_to_palindrome(s):
    chars = list(s)
    moves = 0
    left, right = 0, len(chars) - 1
    while left < right:
        k = right
        while k > left and chars[k] != chars[left]:
            k -= 1
        if k == left:
            chars[left], chars[left + 1] = chars[left + 1], chars[left]
            moves += 1
        else:
            while k < right:
                chars[k], chars[k + 1] = chars[k + 1], chars[k]
                k += 1
                moves += 1
            left += 1
            right -= 1
    return moves
function minMovesToPalindrome(s) {
  const chars = s.split("");
  let moves = 0;
  let left = 0, right = chars.length - 1;
  while (left < right) {
    let k = right;
    while (k > left && chars[k] !== chars[left]) k--;
    if (k === left) {
      [chars[left], chars[left + 1]] = [chars[left + 1], chars[left]];
      moves++;
    } else {
      while (k < right) {
        [chars[k], chars[k + 1]] = [chars[k + 1], chars[k]];
        k++;
        moves++;
      }
      left++;
      right--;
    }
  }
  return moves;
}
int minMovesToPalindrome(String s) {
    char[] chars = s.toCharArray();
    int moves = 0;
    int left = 0, right = chars.length - 1;
    while (left < right) {
        int k = right;
        while (k > left && chars[k] != chars[left]) k--;
        if (k == left) {
            char t = chars[left]; chars[left] = chars[left + 1]; chars[left + 1] = t;
            moves++;
        } else {
            while (k < right) {
                char t = chars[k]; chars[k] = chars[k + 1]; chars[k + 1] = t;
                k++;
                moves++;
            }
            left++;
            right--;
        }
    }
    return moves;
}
int minMovesToPalindrome(string s) {
    int moves = 0;
    int left = 0, right = (int)s.size() - 1;
    while (left < right) {
        int k = right;
        while (k > left && s[k] != s[left]) k--;
        if (k == left) {
            swap(s[left], s[left + 1]);
            moves++;
        } else {
            while (k < right) {
                swap(s[k], s[k + 1]);
                k++;
                moves++;
            }
            left++;
            right--;
        }
    }
    return moves;
}
Time: O(n²) Space: O(n)