#3171

Find Subarray With Bitwise OR Closest to K

Hard
ArrayBinary SearchBit ManipulationSegment TreeSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the properties of bitwise OR and a sliding window approach to efficiently find the closest OR value to k without recalculating the OR for every subarray.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize a variable to store the minimum absolute difference as infinity.
  2. 2Step 2: Use two pointers to represent the current subarray's start and end.
  3. 3Step 3: Expand the end pointer to include more elements and calculate the bitwise OR.
  4. 4Step 4: For each new OR value, calculate the absolute difference with k and update the minimum difference.
  5. 5Step 5: If the OR value exceeds k, move the start pointer to reduce the OR value.
  6. 6Step 6: Repeat until all elements are processed.
solution.py17 lines
1# Full working Python code
2
3def min_abs_diff_optimal(nums, k):
4    min_diff = float('inf')
5    n = len(nums)
6    current_or = 0
7    start = 0
8    for end in range(n):
9        current_or |= nums[end]
10        while start <= end and current_or > k:
11            current_or ^= nums[start]
12            start += 1
13        min_diff = min(min_diff, abs(current_or - k))
14    return min_diff
15
16# Example usage
17print(min_abs_diff_optimal([1, 2, 4, 5], 3))  # Output: 0

Complexity note: The time complexity is O(n) because we traverse the array with two pointers, ensuring each element is processed a limited number of times. The space complexity is O(1) as we only use a few variables for tracking the current state.

  • 1The bitwise OR operation can only add bits, never remove them, which allows for efficient tracking of OR values.
  • 2Using a sliding window helps to dynamically adjust the subarray without recalculating from scratch.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.