Ctrl K

Window OR Closest to a Target

Hard
You are given an integer array values and a number target. A window is a non-empty run of consecutive elements values[l..r]. The value of a window is the bitwise OR of all its elements: values[l] OR values[l + 1] OR ... OR values[r]. Pick the window whose value is closest to target and return the smallest possible gap |target − window value|.
Example 1
values=[4, 1, 8, 2], target=6 → 1

The window [4, 1] gives 4 OR 1 = 5, while [4, 1, 8] already gives 13. No window gives exactly 6; the closest is 5, so the answer is |6 − 5| = 1.

Example 2
values=[3, 5, 6], target=7 → 0

5 OR 6 = 7, exactly the target.

Example 3
values=[16, 16], target=3 → 13

Every window gives 16, so the gap is 13.

Constraints
  • 1 ≤ values.length ≤ 10⁵
  • 0 ≤ values[i], target < 2³¹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAND of a Stretch Near the Goal HardAND Pieces With Cheap Tails HardStretches With an Exact AND HardSmaller Values to the Right HardWindow Sums Within a Band Hard
loading Python…
Input
values=[4, 1, 8, 2], target=6
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 127 tests on the server, hidden ones included.