4021. Minimum Operations to Make a Rotated Palindrome I
Description
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.
Solutions
Solution 1: Enumeration
Thinking
There are only \(n\le 2000\) left rotations, and pairing characters after each rotation is \(O(n^2)\), which fits the limit.
Letters may only increment around the alphabet, so the cheapest way to equalise a pair is the shorter arc \(\min(d,26-d)\); the optimal target is one of the two letters.
Adding the rotation cost \(k\) to every pair's increment cost and taking the minimum yields the answer.
We enumerate the number of left rotations \(k\) (\(0 \leq k < n\)), which costs \(k\) operations. After \(k\) left rotations, index \(i\) in the new string corresponds to index \((i + k) \bmod n\) in the original string.
For each pair of symmetric positions, we need to make the two characters the same by increment operations. Since we can only increment forward ('z' wraps to 'a'), the minimum number of increments to make two letters equal is the shorter arc length on the letter ring, i.e., \(\min(d, 26 - d)\), where \(d\) is the absolute difference of their letter indices. The optimal target letter is always one of the two letters.
We take the minimum over all \(k\).
The time complexity is \(O(n^2)\), and the space complexity is \(O(1)\), where \(n\) is the length of the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |