Find Subarray With Bitwise OR Closest to K - Problem
You are given an array nums and an integer k. You need to find a subarray of nums such that the absolute difference between k and the bitwise OR of the subarray elements is as small as possible.
In other words, select a subarray nums[l..r] such that |k - (nums[l] OR nums[l + 1] ... OR nums[r])| is minimum.
Return the minimum possible value of the absolute difference.
A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Perfect Match
$
Input:
nums = [1,2,4,8], k = 6
›
Output:
0
💡 Note:
Subarray [2,4] has OR = 2|4 = 6, so |6-6| = 0 is the minimum possible difference
Example 2 — Close Match
$
Input:
nums = [1,3,1,3], k = 2
›
Output:
1
💡 Note:
Subarray [1] has OR = 1, and |2-1| = 1. Subarray [3] has OR = 3, and |2-3| = 1. Both give minimum difference of 1
Example 3 — Single Element
$
Input:
nums = [7], k = 5
›
Output:
2
💡 Note:
Only one subarray possible: [7] with OR = 7. Difference is |5-7| = 2
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- 1 ≤ k ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array of integers and target k
2
Compute OR Values
Calculate OR for all possible subarrays
3
Find Minimum
Return minimum |k - OR| difference
Key Takeaway
🎯 Key Insight: OR operation only adds bits, so we can efficiently track unique OR values without redundant calculations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code