Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Sliding Window
Using a strategy of managing the window elements, we can use two pointers to keep track of the current window.
To find the minimum length special subarray ending at index end, we consider our current window [0, end] (both inclusive) and calculate its bitwise OR based on a 32-bit array and a result num.
If num is less than k, we expand the window by including the next element nums[end + 1]. We continue this process until we find a special subarray where num is at least k. At this point, we have a candidate for the answer.
Next, we attempt to minimise the length by shrinking the window from the left side while maintaining the special condition num >= k.
Once shrinking the window causes the special condition to be false (num becomes less than k), we remember that the previous window [start', end'] was valid and found a possible answer end' - start' + 1.
Then, for finding the special subarray ending at index end' + 1, we start from start' + 1 instead of completely restarting. Since we have already found a possible answer of length end' - start' + 1, we only consider shorter lengths moving forward.
This technique leverages two pointers for an efficient sliding window approach.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n),- The primary loop runs from
end = 0toend = n-1, which isO(n). - The
update(bits, nums[end], 1)andupdate(bits, nums[start], -1)each have a complexity ofO(32)because the loop withinupdateruns for a fixed number of 32 iterations (since we are dealing with 32-bit integers). - In the worst-case scenario, the
startpointer can be incremented up tontimes. Given that each increment includes a call tobits_to_num(bits), which runs inO(32), this can happenntimes in total, leading to an additive term ofO(32n).
- The primary loop runs from
- 🧺 Space complexity:
O(1)