Problem Description
Given an array of non-negative integers, find the length of the shortest non-empty contiguous subarray such that the bitwise OR of all its elements is at least k. If no such subarray exists, return -1.
Key Insights
- The OR operation is cumulative but not invertible; meaning when sliding a window, removing an element does not simply subtract its contribution.
- We can combine current numbers with previously computed ORs from subarrays ending at prior positions.
- By maintaining a list of OR-values and their corresponding subarray lengths for subarrays ending at the current index, we can update these values efficiently.
- Redundant OR values (duplicates) can be pruned to keep the dynamic programming state minimal.
- The solution leverages bit manipulation with a dynamic programming approach that iterates through the array while updating the best (shortest) subarray length.
Space and Time Complexity
Time Complexity: O(n * B) where B is the number of bits (in practice at most 32), so effectively O(n).
Space Complexity: O(n) in worst-case scenario, but typically much less as updates merge redundant states.
Solution
We iterate over the array and for each element, we form a new set of subarrays ending at that element by taking the current element alone and by appending it to each subarray ending at the previous index. We compute the new OR value when combining and update the minimal length when the OR reaches at least k. Redundant or duplicate OR values with no advantage in length are removed to keep the state small. This dynamic programming method ensures that we explore all subarrays ending at the current index without needing to re-start from scratch.