Given an array of non-negative integers nums
and an integer K
, find the length of the shortest, non-empty subarray of nums
such that the bitwise OR of every element in the subarray is at least K
. If no such subarray exists, return -1.
nums
be zero?
K
have?
K
can be any non-negative integer.K
be zero?
K
can also be zero. In which case, any non-empty subarray will meet the condition.nums
?
K
), try to minimize the window by moving the left pointer to the right while keeping the condition satisfied.def shortest_subarray_with_or_at_least_k(nums, K):
n = len(nums)
min_len = float('inf')
current_or = 0
left = 0
for right in range(n):
current_or |= nums[right] # Expand the window
while left <= right and current_or >= K: # Contract the window
min_len = min(min_len, right - left + 1)
current_or ^= nums[left] # Remove the leftmost element from OR
left += 1
return min_len if min_len != float('inf') else -1
# Example usage:
nums = [1, 2, 3, 4, 5]
K = 7
print(shortest_subarray_with_or_at_least_k(nums, K)) # Output: Expected subarray length
The sliding window approach ensures that we efficiently find the shortest subarray by maintaining the minimal required checks and updates.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?