Minimum Operations to Make a Rotated Palindrome II Problem
Description
LeetCode Problem 4028.
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 <= 5 * 10^4sconsists only of lowercase English letters.
Solution
Approach: FFT
This is the harder version of the rotated-palindrome problem: n can reach 5 * 10^4, so trying every rotation and pairing characters one by one is too slow.
After k left rotations, position p of the new string is position (p + k) % n of the original. A palindrome pair (p, n - 1 - p) therefore has original indices whose sum is 2k + n - 1 modulo n, the same for every pair. So the cost of rotation k depends only on c = (2k + n - 1) % n: it is the sum, over all index pairs (i, j) with i + j = c (mod n), of the cost of making s[i] and s[j] equal. That cost is the shorter arc min(d, 26 - d) between the two letters on the 26-letter ring.
Such sums over all c at once are a convolution. Expanding the ring-distance function with a discrete Fourier transform over 26 values, map each letter x to the phase e^(2*pi*i*t*x/26) for each frequency t, convolve with an FFT, and combine with the transform weights. The distance function is even, so frequencies 0..13 are enough. Every pair is counted twice and the transform adds a factor of 26, so divide by 52 and round to get the exact cost.
The answer is the minimum over k of k plus the cost for c. (The Python tab does the same convolution with exact big-number multiplication, because plain Python has no FFT.)
Complexity: time O(n log n), space O(n).
from decimal import Context, Decimal, MAX_EMAX, MAX_PREC
class Solution:
def minOperations(self, s: str) -> int:
n = len(s)
rev = s[::-1]
# Polynomial products of exact big decimals (6 digits per slot: a slot sums at most n distances of at most 13) replace the FFT.
ctx = Context(prec=MAX_PREC, Emax=MAX_EMAX)
total = Decimal(0)
letters = "abcdefghijklmnopqrstuvwxyz"
for a in range(26):
# ones[j] = 1 if s[j] is letter a; dist[j] = ring distance between s[j] and a
ones = rev.translate({97 + x: "000001" if x == a else "000000" for x in range(26)})
dist = rev.translate({97 + x: "%06d" % min((a - x) % 26, (x - a) % 26) for x in range(26)})
if letters[a] in s:
total = ctx.add(total, ctx.multiply(Decimal(ones), Decimal(dist)))
digits = format(total, "f").rjust(12 * n, "0")
# pair-cost sums for every index sum i + j, slot p of the product
L = len(digits)
conv = [int(digits[L - 6 * (p + 1): L - 6 * p]) for p in range(2 * n)]
ans = float('inf')
for k in range(n):
c = (2 * k + n - 1) % n
ans = min(ans, k + (conv[c] + conv[c + n]) // 2)
return ans