Problem Description
Given an integer array arr and an integer target, find two indices l and r (0 <= l, r < arr.length) such that |func(arr, l, r) - target| is minimized. The mysterious function func computes the bitwise AND of the subarray arr[l...r]. Return the minimum possible value of |func(arr, l, r) - target|.
Key Insights
- The function func(arr, l, r) is the bitwise AND of a contiguous subarray.
- The bitwise AND result is non-increasing when extending a subarray: once a bit is dropped (set to zero), it will remain 0.
- For any fixed ending index, there are only a limited number (approximately O(log(max(arr[i])))) of distinct bitwise AND values.
- Maintaining a set of distinct results for subarrays ending at the current index avoids recomputation and naturally handles duplicate values.
- As the search proceeds, if an exact match (difference of zero) is found, the algorithm can terminate early.
Space and Time Complexity
Time Complexity: O(n * log(max(arr[i]))), where n is the number of elements in arr. Space Complexity: O(log(max(arr[i]))), due to maintaining the set of distinct bitwise AND values per iteration.
Solution
The solution iterates through the array, keeping track of all distinct bitwise AND values of subarrays that end at the current index. For each new element:
- Start a new subarray with the current element.
- Extend every subarray ending at the previous index by taking the bitwise AND with the current element.
- Update the answer by computing the absolute difference between each distinct AND result and the target.
- If a subarray produces an exact match to the target (difference equals zero), return 0 immediately.
- Continue updating the set for further positions.
This dynamic programming approach efficiently explores all subarrays without the need for a brute-force O(n²) solution.