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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.
Return the minimum possible value of |func(arr, l, r) - target|.
Notice that func should be called with the values l and r where 0 <= l, r < arr.length.
Example 1:
Input: arr = [9,12,3,7,15], target = 5 Output: 2 Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.
Example 2:
Input: arr = [1000000,1000000,1000000], target = 1 Output: 999999 Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.
Example 3:
Input: arr = [1,2,4,8,16], target = 0 Output: 0
Constraints:
1 <= arr.length <= 1051 <= arr[i] <= 1060 <= target <= 107Problem summary: Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target|. Notice that func should be called with the values l and r where 0 <= l, r < arr.length.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Bit Manipulation · Segment Tree
[9,12,3,7,15] 5
[1000000,1000000,1000000] 1
[1,2,4,8,16] 0
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1521: Find a Value of a Mysterious Function Closest to Target
class Solution {
public int closestToTarget(int[] arr, int target) {
int ans = Math.abs(arr[0] - target);
Set<Integer> pre = new HashSet<>();
pre.add(arr[0]);
for (int x : arr) {
Set<Integer> cur = new HashSet<>();
for (int y : pre) {
cur.add(x & y);
}
cur.add(x);
for (int y : cur) {
ans = Math.min(ans, Math.abs(y - target));
}
pre = cur;
}
return ans;
}
}
// Accepted solution for LeetCode #1521: Find a Value of a Mysterious Function Closest to Target
func closestToTarget(arr []int, target int) int {
ans := abs(arr[0] - target)
pre := map[int]bool{arr[0]: true}
for _, x := range arr {
cur := map[int]bool{x: true}
for y := range pre {
cur[x&y] = true
}
for y := range cur {
ans = min(ans, abs(y-target))
}
pre = cur
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #1521: Find a Value of a Mysterious Function Closest to Target
class Solution:
def closestToTarget(self, arr: List[int], target: int) -> int:
ans = abs(arr[0] - target)
s = {arr[0]}
for x in arr:
s = {x & y for y in s} | {x}
ans = min(ans, min(abs(y - target) for y in s))
return ans
// Accepted solution for LeetCode #1521: Find a Value of a Mysterious Function Closest to Target
struct Solution;
use std::collections::HashSet;
impl Solution {
fn closest_to_target(arr: Vec<i32>, target: i32) -> i32 {
let mut prev: HashSet<i32> = HashSet::new();
let n = arr.len();
let mut res = std::i32::MAX;
for i in 0..n {
let mut cur = HashSet::new();
for x in prev {
cur.insert(x & arr[i]);
}
cur.insert(arr[i]);
for &x in &cur {
res = res.min((x - target).abs());
}
prev = cur;
}
res
}
}
#[test]
fn test() {
let arr = vec![9, 12, 3, 7, 15];
let target = 5;
let res = 2;
assert_eq!(Solution::closest_to_target(arr, target), res);
let arr = vec![1000000, 1000000, 1000000];
let target = 1;
let res = 999999;
assert_eq!(Solution::closest_to_target(arr, target), res);
let arr = vec![1, 2, 4, 8, 16];
let target = 0;
let res = 0;
assert_eq!(Solution::closest_to_target(arr, target), res);
}
// Accepted solution for LeetCode #1521: Find a Value of a Mysterious Function Closest to Target
function closestToTarget(arr: number[], target: number): number {
let ans = Math.abs(arr[0] - target);
let pre = new Set<number>();
pre.add(arr[0]);
for (const x of arr) {
const cur = new Set<number>();
cur.add(x);
for (const y of pre) {
cur.add(x & y);
}
for (const y of cur) {
ans = Math.min(ans, Math.abs(y - target));
}
pre = cur;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
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: 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.