1645. Find a Value of a Mysterious Function Closest to Target
My accepted Python solution to LeetCode problem 1645, Find a Value of a Mysterious Function Closest to Target, running in 514ms.
- Difficulty: Hard
- Python
- Runtime 514ms
- Memory 26.7MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 514ms, memory 26.7MB, accepted 2025-12-24.
class Solution:
def closestToTarget(self, arr: List[int], target: int) -> int:
result = float('inf')
current = set()
for num in arr:
# Each element ANDed with all previous cumulative ANDs
current = {num & prev for prev in current} | {num}
# Check each value against target
for val in current:
result = min(result, abs(val - target))
return result