Find Subarray With Bitwise OR Closest to K - Problem
Find the Perfect Bitwise OR Match!
Given an array
The bitwise OR of a subarray combines all bits using the OR operation: if any element has a bit set at position
Goal: Find a subarray
Example: For
⢠Subarray
⢠This is optimal since we found an exact match!
Return the minimum possible absolute difference.
Given an array
nums and a target integer k, you need to find a contiguous subarray whose bitwise OR value is as close as possible to k.The bitwise OR of a subarray combines all bits using the OR operation: if any element has a bit set at position
i, the result will have that bit set too.Goal: Find a subarray
nums[l..r] that minimizes |k - (nums[l] OR nums[l+1] OR ... OR nums[r])|Example: For
nums = [1, 2, 4, 5] and k = 3:⢠Subarray
[1, 2] has OR = 1 | 2 = 3, difference = |3 - 3| = 0⢠This is optimal since we found an exact match!
Return the minimum possible absolute difference.
Input & Output
example_1.py ā Basic Case
$
Input:
nums = [1,2,4,5], k = 3
āŗ
Output:
0
š” Note:
The subarray [1,2] has OR value 1|2 = 3, which exactly matches k=3. The absolute difference is |3-3| = 0, which is optimal.
example_2.py ā No Exact Match
$
Input:
nums = [1,3,1,3], k = 2
āŗ
Output:
1
š” Note:
All possible OR values are 1 (from [1]), 3 (from [3] or [1,3]), giving differences |2-1|=1 and |2-3|=1. The minimum difference is 1.
example_3.py ā Single Element
$
Input:
nums = [1], k = 10
āŗ
Output:
9
š” Note:
Only one subarray [1] exists with OR value 1. The absolute difference is |10-1| = 9.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Paint Palette
We have paints [1,2,4,5] and want to match color k=3
2
Try Mixing from Position 0
Start with paint 1, then try 1+2, then 1+2+4, etc.
3
Check Color Match
Paint 1|2 = 3 gives perfect match! Difference = 0
4
Verify Optimality
Continue checking other combinations but none beat difference of 0
Key Takeaway
šÆ Key Insight: The OR operation can only set bits (never unset them), which means there are at most 32 distinct OR values when extending from any starting position. This property allows us to optimize from O(n³) to O(n) time complexity!
Time & Space Complexity
Time Complexity
O(n log n)
For each position, at most 32 distinct OR values, leading to O(32n) = O(n)
ā” Linearithmic
Space Complexity
O(log n)
At most 32 distinct OR values stored in set at any time
ā” Linearithmic Space
Constraints
- 1 ⤠nums.length ⤠105
- 1 ⤠nums[i] ⤠109
- 1 ⤠k ⤠109
- All array elements and k are positive integers
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code