#3766

Minimum Operations to Make Binary Palindrome

Medium
ArrayTwo PointersBinary SearchBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Precompute binary palindromes and find the closest one for each number using binary search. This reduces the search space significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute binary palindromes up to a reasonable limit.
  2. 2Step 2: For each number in nums, use binary search to find the closest binary palindrome.
  3. 3Step 3: Calculate the difference and store the result.
solution.py2 lines
1def generate_palindromes(limit): return [i for i in range(limit) if bin(i)[2:] == bin(i)[2:][::-1]]
2def min_operations(nums): palindromes = generate_palindromes(10000); return [min(abs(n - p) for p in palindromes) for n in nums]

Complexity note: Precomputing palindromes takes linear time, and searching them is efficient due to the reduced size.

  • 1Binary representation is crucial for palindrome checks.
  • 2Precomputation of palindromes reduces repeated calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.