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
Find Subarray With Bitwise OR Closest to K INPUT nums array: 1 i=0 2 i=1 4 i=2 8 i=3 Binary: 0001 0010 0100 1000 Target k: 6 k in binary: 0110 Goal: Find subarray with OR closest to k=6 min |k - OR(subarray)| ALGORITHM STEPS 1 Track OR values Maintain set of all ORs ending at current index 2 Update OR set For each num, OR with all prev values + itself 3 Check differences Calculate |k - OR| for each OR value 4 Track minimum Update min diff when smaller found Trace: i=0: ORs={1} |6-1|=5 i=1: ORs={2,3} |6-3|=3 i=2: ORs={4,6,7} |6-6|=0 i=3: ORs={8,..} (already 0) OK FINAL RESULT Optimal Subarray Found: 2 4 nums[1..2] Bitwise OR: 2 = 0010 4 = 0100 OR = 0110 = 6 |k - OR| = |6 - 6| = 0 Output: 0 Key Insight: Bitwise OR is monotonically increasing - once a bit is set, it stays set. This means as we extend a subarray, OR can only increase or stay same. The number of distinct OR values ending at any index is at most O(log max(nums)) since each step can only add new bits. This gives O(n log M) time. TutorialsPoint - Find Subarray With Bitwise OR Closest to K | Single Pass Optimization
Asked in
Google 35 Microsoft 28 Amazon 22
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen