[LeetCode] Minimum Operations to Make a Rotated Palindrome I

4021. Minimum Operations to Make a Rotated Palindrome I

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 i and replace s[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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int minOperations(string s) {
int n = s.size();
int res = INT_MAX;

for(int shift = 0; shift < n; shift++) {
int cost = shift;

for(int i = 0; i < n / 2; i++) {
int a = s[(shift + i) % n] - 'a';
int b = s[(shift + n - 1 - i) % n] - 'a';

cost += min((a - b + 26) % 26,
(b - a + 26) % 26);
}

res = min(res, cost);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/03/PS/LeetCode/minimum-operations-to-make-a-rotated-palindrome-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.