4099. Minimum Operations to Make Binary Palindrome
My accepted Python solution to LeetCode problem 4099, Minimum Operations to Make Binary Palindrome, running in 1574ms.
- Difficulty: Medium
- Python
- Runtime 1574ms
- Memory 18.1MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 1574ms, memory 18.1MB, accepted 2025-12-29.
class Solution:
def minOperations(self, nums: List[int]) -> List[int]:
def min_ops(n):
if n == 0:
return 0 # 0 in binary is "0", already palindrome
# Get binary representation without '0b' prefix
binary = bin(n)[2:]
length = len(binary)
# BFS to find minimum operations
from collections import deque
visited = {n}
q = deque([(n, 0)])
def is_palindrome(num):
if num == 0:
return True
b = bin(num)[2:]
return b == b[::-1]
while q:
curr, ops = q.popleft()
if is_palindrome(curr):
return ops
# Try +1 and -1
for next_val in [curr + 1, curr - 1]:
if next_val >= 0 and next_val not in visited:
visited.add(next_val)
q.append((next_val, ops + 1))
return -1 # Should never reach here
return [min_ops(num) for num in nums]