Minimum Operations to Make Every Element Palindromic Problem
Description
LeetCode Problem 4053.
You are given an integer array nums.
In one operation, you may choose an index i and either increment or decrement nums[i] by 2.
Return the minimum number of operations required to make every element in nums a positive palindrome. Different elements may be changed into different palindromic integers.
Example 1:
Input: nums = [10,12,14,16]
Output: 9
Explanation:
One optimal sequence of operations is:
- Decrement nums[0] by 2 once to change it from 10 to 8.
- Decrement nums[1] by 2 twice to change it from 12 to 8.
- Decrement nums[2] by 2 three times to change it from 14 to 8.
- Increment nums[3] by 2 three times to change it from 16 to 22.
After 1 + 2 + 3 + 3 = 9 operations, nums = [8, 8, 8, 22], and every element is a positive palindromic integer.
It can be shown that fewer than 9 operations cannot achieve this.
Example 2:
Input: nums = [9,10,11,10]
Output: 2
Explanation:
Decrement nums[1] and nums[3] by 2 once each.
After 2 operations, nums = [9, 8, 11, 8], and every element is a positive palindromic integer.
At least one operation is needed for each of these two elements, so the minimum number of operations is 2.
Example 3:
Input: nums = [125]
Output: 2
Explanation:
Decrement nums[0] by 2 twice to change it from 125 to 121, which is a positive palindromic integer.
A single operation would change it to 123 or 127, neither of which is palindromic. Thus, the minimum number of operations is 2.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Precomputed Palindromes and Binary Search
An operation changes an element by 2, so its parity never changes: the target palindrome must have the same parity as the element. The elements are independent, so for each x we find the nearest positive palindrome p of the same parity and add |x - p| / 2.
Precompute the palindromes. For every i from 1 to 100000, let s be its decimal string and build s + reverse(s) (even length) and s + reverse(s without its last digit) (odd length). That covers every palindrome with up to about 11 digits, enough for values up to 10^9. Split them into two sorted lists by parity.
For each x, binary search the first palindrome that is at least x in the list of its parity, compare it with the one before it, and take the smaller distance divided by 2.
Complexity: O(M log M + n log M) time and O(M) space, where M (about 200000) is the number of palindromes.
from bisect import bisect_left
ps = [[], []]
for i in range(1, 10**5 + 1):
s = str(i)
t1 = s[::-1]
t2 = s[:-1][::-1]
x = int(s + t1)
ps[x & 1].append(x)
y = int(s + t2)
ps[y & 1].append(y)
for p in ps:
p.sort()
class Solution:
def minOperations(self, nums: List[int]) -> int:
ans = 0
for x in nums:
p = ps[x & 1]
i = bisect_left(p, x)
t = 10**18
if i < len(p):
t = p[i] - x
if i:
t = min(t, x - p[i - 1])
ans += t // 2
return ans