#3766
Minimum Operations to Make Binary Palindrome
MediumArrayTwo PointersBinary SearchBit ManipulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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- 1Step 1: Precompute binary palindromes up to a reasonable limit.
- 2Step 2: For each number in nums, use binary search to find the closest binary palindrome.
- 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.