Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: nums = [1,2,4,5], k = 3
Output: 0
Explanation:
The subarray nums[0..1] has OR value 3, which gives the minimum absolute difference |3 - 3| = 0.
Example 2:
Input: nums = [1,3,1,3], k = 2
Output: 1
Explanation:
The subarray nums[1..1] has OR value 3, which gives the minimum absolute difference |3 - 2| = 1.
Example 3:
Input: nums = [1], k = 10
Output: 9
Explanation:
There is a single subarray with OR value 1, which gives the minimum absolute difference |10 - 1| = 9.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1091 <= k <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Bit Manipulation · Segment Tree
[1,2,4,5] 3
[1,3,1,3] 2
[1] 10
minimum-sum-of-values-by-dividing-array)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3171: Find Subarray With Bitwise OR Closest to K
class Solution {
public int minimumDifference(int[] nums, int k) {
int mx = 0;
for (int x : nums) {
mx = Math.max(mx, x);
}
int m = 32 - Integer.numberOfLeadingZeros(mx);
int[] cnt = new int[m];
int n = nums.length;
int ans = Integer.MAX_VALUE;
for (int i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
ans = Math.min(ans, Math.abs(s - k));
for (int h = 0; h < m; ++h) {
if ((nums[j] >> h & 1) == 1) {
++cnt[h];
}
}
while (i < j && s > k) {
for (int h = 0; h < m; ++h) {
if ((nums[i] >> h & 1) == 1 && --cnt[h] == 0) {
s ^= 1 << h;
}
}
++i;
ans = Math.min(ans, Math.abs(s - k));
}
}
return ans;
}
}
// Accepted solution for LeetCode #3171: Find Subarray With Bitwise OR Closest to K
func minimumDifference(nums []int, k int) int {
m := bits.Len(uint(slices.Max(nums)))
cnt := make([]int, m)
ans := math.MaxInt32
s, i := 0, 0
for j, x := range nums {
s |= x
ans = min(ans, abs(s-k))
for h := 0; h < m; h++ {
if x>>h&1 == 1 {
cnt[h]++
}
}
for i < j && s > k {
y := nums[i]
for h := 0; h < m; h++ {
if y>>h&1 == 1 {
cnt[h]--
if cnt[h] == 0 {
s ^= 1 << h
}
}
}
ans = min(ans, abs(s-k))
i++
}
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #3171: Find Subarray With Bitwise OR Closest to K
class Solution:
def minimumDifference(self, nums: List[int], k: int) -> int:
m = max(nums).bit_length()
cnt = [0] * m
s = i = 0
ans = inf
for j, x in enumerate(nums):
s |= x
ans = min(ans, abs(s - k))
for h in range(m):
if x >> h & 1:
cnt[h] += 1
while i < j and s > k:
y = nums[i]
for h in range(m):
if y >> h & 1:
cnt[h] -= 1
if cnt[h] == 0:
s ^= 1 << h
i += 1
ans = min(ans, abs(s - k))
return ans
// Accepted solution for LeetCode #3171: Find Subarray With Bitwise OR Closest to K
/**
* [3171] Find Subarray With Bitwise OR Closest to K
*/
pub struct Solution {}
// submission codes start here
use std::cmp::Ordering;
impl Solution {
pub fn minimum_difference(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
let mut bits_max_pos = vec![None; 31];
let mut pos_to_bit = Vec::with_capacity(31);
let mut result = i32::MAX;
for i in 0..n {
for j in 0..=30 {
if nums[i] >> j & 1 == 1 {
bits_max_pos[j] = Some(i)
}
}
pos_to_bit.clear();
for j in 0..=30 {
if let Some(pos) = bits_max_pos[j] {
pos_to_bit.push((pos, j));
}
}
pos_to_bit.sort_by(|a, b| match b.0.cmp(&a.0) {
Ordering::Less => Ordering::Less,
Ordering::Equal => b.1.cmp(&a.1),
Ordering::Greater => Ordering::Greater,
});
let mut value = 0;
let (mut left, mut right) = (0, 0);
while right < pos_to_bit.len() {
while right < pos_to_bit.len() && pos_to_bit[right].0 == pos_to_bit[left].0 {
value |= 1 << pos_to_bit[right].1;
right += 1;
}
result = result.min((value - k).abs());
left = right;
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3171() {
assert_eq!(0, Solution::minimum_difference(vec![1, 2, 4, 5], 3));
assert_eq!(1, Solution::minimum_difference(vec![1, 3, 1, 3], 2));
assert_eq!(9, Solution::minimum_difference(vec![1], 10));
}
}
// Accepted solution for LeetCode #3171: Find Subarray With Bitwise OR Closest to K
function minimumDifference(nums: number[], k: number): number {
const m = Math.max(...nums).toString(2).length;
const n = nums.length;
const cnt: number[] = Array(m).fill(0);
let ans = Infinity;
for (let i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
ans = Math.min(ans, Math.abs(s - k));
for (let h = 0; h < m; ++h) {
if ((nums[j] >> h) & 1) {
++cnt[h];
}
}
while (i < j && s > k) {
for (let h = 0; h < m; ++h) {
if ((nums[i] >> h) & 1 && --cnt[h] === 0) {
s ^= 1 << h;
}
}
ans = Math.min(ans, Math.abs(s - k));
++i;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.