Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer array nums.
For each element nums[i], you may perform the following operations any number of times (including zero):
nums[i] by 1, ornums[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] <= 5000Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Binary Search · Bit Manipulation
[1,2,4]
[6,7,12]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3766: Minimum Operations to Make Binary Palindrome
class Solution {
private static final List<Integer> p = new ArrayList<>();
static {
int N = 1 << 14;
for (int i = 0; i < N; i++) {
String s = Integer.toBinaryString(i);
String rs = new StringBuilder(s).reverse().toString();
if (s.equals(rs)) {
p.add(i);
}
}
}
public int[] minOperations(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
Arrays.fill(ans, Integer.MAX_VALUE);
for (int k = 0; k < n; ++k) {
int x = nums[k];
int i = binarySearch(p, x);
if (i < p.size()) {
ans[k] = Math.min(ans[k], p.get(i) - x);
}
if (i >= 1) {
ans[k] = Math.min(ans[k], x - p.get(i - 1));
}
}
return ans;
}
private int binarySearch(List<Integer> p, int x) {
int l = 0, r = p.size();
while (l < r) {
int mid = (l + r) >>> 1;
if (p.get(mid) >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
// Accepted solution for LeetCode #3766: Minimum Operations to Make Binary Palindrome
var p []int
func init() {
N := 1 << 14
for i := 0; i < N; i++ {
s := strconv.FormatInt(int64(i), 2)
if isPalindrome(s) {
p = append(p, i)
}
}
}
func isPalindrome(s string) bool {
runes := []rune(s)
for i := 0; i < len(runes)/2; i++ {
if runes[i] != runes[len(runes)-1-i] {
return false
}
}
return true
}
func minOperations(nums []int) []int {
ans := make([]int, len(nums))
for k, x := range nums {
i := sort.SearchInts(p, x)
t := math.MaxInt32
if i < len(p) {
t = p[i] - x
}
if i >= 1 {
t = min(t, x-p[i-1])
}
ans[k] = t
}
return ans
}
# Accepted solution for LeetCode #3766: Minimum Operations to Make Binary Palindrome
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
// Accepted solution for LeetCode #3766: Minimum Operations to Make Binary Palindrome
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3766: Minimum Operations to Make Binary Palindrome
// class Solution {
// private static final List<Integer> p = new ArrayList<>();
//
// static {
// int N = 1 << 14;
// for (int i = 0; i < N; i++) {
// String s = Integer.toBinaryString(i);
// String rs = new StringBuilder(s).reverse().toString();
// if (s.equals(rs)) {
// p.add(i);
// }
// }
// }
//
// public int[] minOperations(int[] nums) {
// int n = nums.length;
// int[] ans = new int[n];
// Arrays.fill(ans, Integer.MAX_VALUE);
// for (int k = 0; k < n; ++k) {
// int x = nums[k];
// int i = binarySearch(p, x);
// if (i < p.size()) {
// ans[k] = Math.min(ans[k], p.get(i) - x);
// }
// if (i >= 1) {
// ans[k] = Math.min(ans[k], x - p.get(i - 1));
// }
// }
//
// return ans;
// }
//
// private int binarySearch(List<Integer> p, int x) {
// int l = 0, r = p.size();
// while (l < r) {
// int mid = (l + r) >>> 1;
// if (p.get(mid) >= x) {
// r = mid;
// } else {
// l = mid + 1;
// }
// }
// return l;
// }
// }
// Accepted solution for LeetCode #3766: Minimum Operations to Make Binary Palindrome
const p: number[] = (() => {
const res: number[] = [];
const N = 1 << 14;
for (let i = 0; i < N; i++) {
const s = i.toString(2);
if (s === s.split('').reverse().join('')) {
res.push(i);
}
}
return res;
})();
function minOperations(nums: number[]): number[] {
const ans: number[] = Array(nums.length).fill(Number.MAX_SAFE_INTEGER);
for (let k = 0; k < nums.length; k++) {
const x = nums[k];
const i = _.sortedIndex(p, x);
if (i < p.length) {
ans[k] = p[i] - x;
}
if (i >= 1) {
ans[k] = Math.min(ans[k], x - p[i - 1]);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.