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
Bitwise AND: The Key to OptimizationBinary Representation:9 = 100112 = 11003 = 00117 = 0111AND Results:9 & 12 = 1000 = 88 & 3 = 0000 = 00 & 7 = 0000 = 0Optimization InsightBit positions can only go from 1 โ†’ 0At most 32 unique values per position (logโ‚‚ of max value)Total time complexity: O(n ร— log(max_val))Result: Dramatic improvement from O(nยณ) to O(n log V)!
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
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
31.2K Views
Medium Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen