Minimum Number of Moves to Make Palindrome — LeetCode 2193 Python Solution
HardGreedyBinary Indexed TreeTwo PointersString
- Problem
- #2193
- Pattern
- Two Pointers
- Reading time
- 4 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(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
LeetCode 680Valid Palindrome IIEasyLeetCode 942DI String MatchEasyLeetCode 1147Longest Chunked Palindrome DecompositionHardLeetCode 1505Minimum Possible Integer After at Most K Adjacent Swaps On DigitsHardLeetCode 1754Largest Merge Of Two StringsMediumLeetCode 1850Minimum Adjacent Swaps to Reach the Kth Smallest NumberMedium
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.