Find a Value of a Mysterious Function Closest to Target - Problem
Winston discovered a mysterious function func(arr, l, r) that performs a bitwise AND operation on all elements in the subarray from index l to index r (inclusive). The function returns arr[l] & arr[l+1] & ... & arr[r].
Given an integer array arr and a target value target, your mission is to find indices l and r such that the absolute difference |func(arr, l, r) - target| is minimized.
Your goal: Return the minimum possible value of |func(arr, l, r) - target|.
Note: Both l and r must satisfy 0 <= l, r < arr.length.
Example: If arr = [9,12,3,7,15] and target = 5, we need to check all possible subarrays and find which one gives us a bitwise AND result closest to 5.
Input & Output
example_1.py โ Basic Case
$
Input:
arr = [9,12,3,7,15], target = 5
โบ
Output:
2
๐ก Note:
We need to find the subarray whose bitwise AND is closest to 5. Checking key subarrays: [3] gives AND=3, difference=2. [7] gives AND=7, difference=2. [3,7] gives AND=3, difference=2. The minimum difference is 2.
example_2.py โ Single Element
$
Input:
arr = [1000000], target = 1
โบ
Output:
999999
๐ก Note:
With only one element, the only possible subarray is [1000000] itself. The bitwise AND is 1000000, so the difference with target 1 is |1000000 - 1| = 999999.
example_3.py โ Exact Match
$
Input:
arr = [1,2,4,8,16], target = 4
โบ
Output:
0
๐ก Note:
The subarray [4] has bitwise AND equal to 4, which exactly matches our target. The difference is |4 - 4| = 0.
Constraints
- 1 โค arr.length โค 105
- 1 โค arr[i] โค 106
- 1 โค target โค 106
- All array elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
AND Monotonicity
Each additional element can only turn bits OFF, creating limited unique values
2
Set Tracking
Track all possible AND values efficiently using a set data structure
3
Optimal Search
Find minimum difference by checking each unique value against target
Key Takeaway
๐ฏ Key Insight: Bitwise AND's monotonic decreasing property limits unique values to at most log(max_value), enabling efficient optimization
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code