Minimum Operations to Make a Rotated Palindrome I Problem
Description
LeetCode Problem 4021.
You are given a string s consisting of lowercase English letters.
You can perform the following operations any number of times (including zero) and in any order:
- Increment: Choose any index
iand replaces[i]with the next lowercase English letter. The letter after'z'is'a'. - Left rotate: Move the first character of the string to the end.
Return the minimum number of operations required to make s a palindrome.
Example 1:
Input: s = "abc"
Output: 2
Explanation:
One optimal solution:
- Left rotate the string: "abc" -> "bca".
- Increment 'a' to 'b': "bca" -> "bcb".
- "bcb" is a palindrome. Thus, the answer is 2.
Example 2:
Input: s = "yb"
Output: 3
Explanation:
- Increment the first character three times: "yb" -> "zb" -> "ab" -> "bb".
- "bb" is a palindrome. Thus, the answer is 3.
Constraints:
2 <= s.length <= 2000sconsists only of lowercase English letters.
Solution
Approach: Enumeration
Try every number of left rotations k in [0, n), which costs k operations. After k rotations, position i of the new string holds the character at index (i + k) % n of the original string.
For each pair of mirrored positions the two letters must become equal using increments, which only move forward around the alphabet (z wraps to a). If d is the difference of the two letters, the cheapest way is min(d, 26 - d) increments: raise one letter up to the other, whichever direction is shorter.
Add these costs for all mirrored pairs and take the minimum over all k.
Complexity: time O(n^2), space O(1), where n is the length of s.
class Solution:
def minOperations(self, s: str) -> int:
n = len(s)
ans = 10**9
for k in range(n):
t = k
i, j = 0, n - 1
while i < j:
x = ord(s[(i + k) % n]) - ord('a')
y = ord(s[(j + k) % n]) - ord('a')
d = abs(x - y)
t += min(d, 26 - d)
i, j = i + 1, j - 1
ans = min(ans, t)
return ans