#3095
Shortest Subarray With OR at Least K I
EasyArrayBit ManipulationSliding WindowSliding WindowBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a sliding window technique to efficiently find the shortest subarray with a bitwise OR of at least k. This reduces the number of checks needed compared to the brute force method.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two pointers for the sliding window and a variable to keep track of the current OR.
- 2Step 2: Expand the right pointer to include elements until the OR is at least k.
- 3Step 3: Once the OR is at least k, try to shrink the left pointer to minimize the window size while maintaining the OR condition.
solution.py14 lines
1# Full working Python code
2
3def shortest_subarray_with_or(nums, k):
4 n = len(nums)
5 left = 0
6 current_or = 0
7 min_length = float('inf')
8 for right in range(n):
9 current_or |= nums[right]
10 while current_or >= k:
11 min_length = min(min_length, right - left + 1)
12 current_or ^= nums[left]
13 left += 1
14 return min_length if min_length != float('inf') else -1ℹ
Complexity note: The time complexity is O(n) because each element is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(1) since we only use a few extra variables.
- 1The bitwise OR operation accumulates bits, meaning once a bit is set to 1, it stays 1 for the rest of the OR operation.
- 2Shortening the subarray while maintaining the OR condition is crucial for optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.