#1521
Find a Value of a Mysterious Function Closest to Target
HardArrayBinary SearchBit ManipulationSegment TreeBit ManipulationSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the properties of the AND operation and uses a binary search approach to efficiently find the closest AND value to the target. This significantly reduces the number of calculations needed.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to store the minimum difference from the target.
- 2Step 2: Iterate through each index i in the array.
- 3Step 3: For each i, calculate the AND value from arr[i] to arr[j] for increasing j until the AND value becomes 0.
- 4Step 4: For each AND value computed, use binary search to find the closest value to the target.
- 5Step 5: Update the minimum difference if the current difference is smaller.
solution.py11 lines
1def closest_value(arr, target):
2 min_diff = float('inf')
3 n = len(arr)
4 for i in range(n):
5 and_value = arr[i]
6 for j in range(i, n):
7 and_value &= arr[j]
8 if and_value == 0:
9 break
10 min_diff = min(min_diff, abs(and_value - target))
11 return min_diffℹ
Complexity note: This complexity is achieved by stopping the inner loop when the AND value becomes 0, significantly reducing unnecessary calculations.
- 1The AND operation is non-increasing, meaning larger ranges will yield smaller or equal values.
- 2Stopping the search when the AND reaches 0 can save unnecessary calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.