LeetCode solutions

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

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 514ms, memory 26.7MB, accepted 2025-12-24.

python
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

Source