Find a Value of a Mysterious Function Closest to Target — LeetCode 1521 Python Solution

HardBit ManipulationSegment TreeArrayBinary Search
Problem
#1521
Reading time
2 min

The problem

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.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(\log M) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1521. Find a Value of a Mysterious Function Closest to Target is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1521. Find a Value of a Mysterious Function Closest to Target?
LeetCode 1521. Find a Value of a Mysterious Function Closest to Target is rated Hard on LeetCode.
What is the time complexity of LeetCode 1521. Find a Value of a Mysterious Function Closest to Target?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 1521. Find a Value of a Mysterious Function Closest to Target?
The Python solution on this page uses O(\log M) auxiliary space.
What topics does LeetCode 1521. Find a Value of a Mysterious Function Closest to Target cover?
LeetCode 1521. Find a Value of a Mysterious Function Closest to Target is tagged Bit Manipulation, Segment Tree, Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview