#2193
Minimum Number of Moves to Make Palindrome
HardTwo PointersStringGreedyBinary Indexed TreeTwo PointersGreedyString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a greedy approach with two pointers to minimize the number of swaps needed to form a palindrome. By always trying to match characters from the outer ends towards the center, we can efficiently determine the minimum moves.
⚙️
Algorithm
6 steps- 1Step 1: Initialize two pointers, left at the start and right at the end of the string.
- 2Step 2: While left is less than right, check if characters at both pointers match.
- 3Step 3: If they match, move both pointers inward.
- 4Step 4: If they do not match, find the nearest matching character for the left pointer by moving the right pointer leftward.
- 5Step 5: Count the number of swaps needed to bring the matching character next to the left pointer.
- 6Step 6: Increment the move counter and continue until the pointers meet.
solution.py29 lines
1# Full working Python code
2
3def min_moves_to_palindrome(s):
4 s = list(s)
5 moves = 0
6 left, right = 0, len(s) - 1
7 while left < right:
8 if s[left] == s[right]:
9 left += 1
10 right -= 1
11 else:
12 r = right
13 while r > left and s[left] != s[r]:
14 r -= 1
15 if r == left:
16 # No match found, swap left with left + 1
17 s[left], s[left + 1] = s[left + 1], s[left]
18 moves += 1
19 else:
20 # Move the matching character to the right
21 for i in range(r, right):
22 s[i], s[i + 1] = s[i + 1], s[i]
23 moves += 1
24 left += 1
25 right -= 1
26 return moves
27
28# Example usage
29print(min_moves_to_palindrome('letelt')) # Output: 2ℹ
Complexity note: The time complexity is O(n) because we only traverse the string a limited number of times, making it efficient. The space complexity is O(n) due to the character array used to manipulate the string.
- 1Greedy strategies often yield optimal solutions for problems involving order and arrangement.
- 2Two pointers can effectively reduce the complexity of problems involving pairs or sequences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.