Minimum Number of Moves to Make Palindrome — LeetCode 2193 Python Solution

HardGreedyBinary Indexed TreeTwo PointersString
Problem
#2193
Reading time
4 min

The 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.

Example

Input
s = "aabb"
Output
2
Explanation
We can obtain two palindromes from s, "abba" and "baab".

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2193. Minimum Number of Moves to Make Palindrome is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2193. Minimum Number of Moves to Make Palindrome?
LeetCode 2193. Minimum Number of Moves to Make Palindrome is rated Hard on LeetCode.
What is the time complexity of LeetCode 2193. Minimum Number of Moves to Make Palindrome?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 2193. Minimum Number of Moves to Make Palindrome?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2193. Minimum Number of Moves to Make Palindrome cover?
LeetCode 2193. Minimum Number of Moves to Make Palindrome is tagged Greedy, Binary Indexed Tree, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview