Shortest Subarray With OR at Least K I Problem
Description
LeetCode Problem 3095.
You are given an array nums of non-negative integers and an integer k.
An array is called special if the bitwise OR of all of its elements is at least k.
Return the length of the shortest special non-empty subarray of nums, or return -1 if no special subarray exists.
Example 1:
Input: nums = [1,2,3], k = 2
Output: 1
Explanation:
The subarray [3] has OR value of 3. Hence, we return 1.
Note that [2] is also a special subarray.
Example 2:
Input: nums = [2,1,8], k = 10
Output: 3
Explanation:
The subarray [2,1,8] has OR value of 11. Hence, we return 3.
Example 3:
Input: nums = [1,2], k = 0
Output: 1
Explanation:
The subarray [1] has OR value of 1. Hence, we return 1.
Constraints:
1 <= nums.length <= 500 <= nums[i] <= 500 <= k < 64
Solution
Approach: Two Pointers + Bit Counts
Extending a subarray to the right can only add bits to its OR, never remove them. That makes a sliding window work: grow the window on the right, and while its OR is at least k, record the length and shrink it from the left.
An OR cannot be undone by simply removing a number, so we keep a counter cnt[h] for each bit h: how many numbers in the window have that bit set. When a number leaves the window, we decrement its bits, and a bit disappears from the OR only when its counter reaches zero.
If no window ever reaches k, the answer is -1.
Complexity: O(n log M) time and O(log M) space, where M is the largest value.
class Solution:
def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
n = len(nums)
cnt = [0] * 32
ans = n + 1
s = i = 0
for j, x in enumerate(nums):
s |= x
for h in range(32):
if x >> h & 1:
cnt[h] += 1
while s >= k and i <= j:
ans = min(ans, j - i + 1)
y = nums[i]
for h in range(32):
if y >> h & 1:
cnt[h] -= 1
if cnt[h] == 0:
s ^= 1 << h
i += 1
return -1 if ans > n else ans