Minimum Operations to Make Binary Palindrome Problem
Description
LeetCode Problem 3766.
You are given an integer array nums.
For each element nums[i], you may perform the following operations any number of times (including zero):
- Increase
nums[i]by 1, or - Decrease
nums[i]by 1.
A number is called a binary palindrome if its binary representation without leading zeros reads the same forward and backward.
Your task is to return an integer array ans, where ans[i] represents the minimum number of operations required to convert nums[i] into a binary palindrome.
Example 1:
Input: nums = [1,2,4]
Output: [0,1,1]
Explanation:
One optimal set of operations:
nums[i] Binary(nums[i]) Nearest Palindrome Binary (Palindrome) Operations Required ans[i]
1 1 1 1 Already palindrome 0
2 10 3 11 Increase by 1 1
4 100 3 11 Decrease by 1 1
Thus, ans = [0, 1, 1].
Example 2:
Input: nums = [6,7,12]
Output: [1,0,3]
Explanation:
One optimal set of operations:
nums[i] Binary(nums[i]) Nearest Palindrome Binary (Palindrome) Operations Required ans[i]
6 110 5 101 Decrease by 1 1
7 111 7 111 Already palindrome 0
12 1100 15 1111 Increase by 3 3
Thus, ans = [1, 0, 3].
Constraints:
1 <= nums.length <= 50001 <= nums[i] <=5000
Solution
Approach: Precompute Palindromes + Binary Search
Every value is at most 5000, and 8191 (binary 1111111111111) is a palindrome above that, so the nearest palindrome always lies below 214. List every number below 214 whose binary form reads the same in both directions, in increasing order.
For each x, binary search that list for the first palindrome p[i] >= x and also look at the one before it, p[i-1] < x. The answer for x is the smaller of p[i] - x and x - p[i-1]. A number that is already a palindrome gets 0.
Complexity: O(M + n log M) time and O(M) space, where M is the number of precomputed palindromes (a few hundred) and n is the length of nums.
from bisect import bisect_left
from math import inf
p = []
for i in range(1 << 14):
s = bin(i)[2:]
if s == s[::-1]:
p.append(i)
class Solution:
def minOperations(self, nums: List[int]) -> List[int]:
ans = []
for x in nums:
i = bisect_left(p, x)
times = inf
if i < len(p):
times = min(times, p[i] - x)
if i >= 1:
times = min(times, x - p[i - 1])
ans.append(times)
return ans