Find a Value of a Mysterious Function Closest to Target Problem
Description
LeetCode Problem 1521.

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 <= 10^51 <= arr[i] <= 10^60 <= target <= 10^7
Solution
Approach: Keep the Few Distinct ANDs Ending at Each Index
The function in the picture computes the bitwise AND arr[l] & arr[l + 1] & ... & arr[r], so we want the subarray whose AND is closest to target. There are O(n2) subarrays, but far fewer distinct AND values.
Fix the right end r and move the left end l leftwards. Each extra element can only turn bits off, so the AND never grows, and every time it changes, at least one bit disappears. Since arr[i] <= 10^6 < 2^20, there are at most about 20 distinct ANDs for subarrays ending at r.
So keep the list ands of distinct ANDs of subarrays ending at the previous index, from the shortest subarray to the longest. For the next element x:
- the new list starts with
xitself (the subarray[x]), - then each old value
ybecomesy & x(the same subarray extended byx), - and since the values keep shrinking, duplicates are next to each other, so we only skip a value equal to the last one we added.
Check every value in the new list against target and keep the smallest |value - target|.
Complexity: O(n log M) time, where M is the largest value (each list has O(log M) values), and O(log M) extra space.
class Solution:
def closestToTarget(self, arr: List[int], target: int) -> int:
ans = abs(arr[0] - target)
ands = [] # distinct ANDs of the subarrays ending at the previous index
for x in arr:
# extend every subarray by x, plus the subarray [x] itself
cur = [x]
for y in ands:
v = y & x
if v != cur[-1]: # the values only shrink, so equal ones are adjacent
cur.append(v)
ands = cur
for v in ands:
ans = min(ans, abs(v - target))
return ans