3097. Shortest Subarray With OR at Least K II
Difficulty: Medium
Topics: Array, Bit Manipulation, Sliding Window
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 subarray1 of nums, or return -1 if no special subarray exists.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We can use a sliding window approach combined with bit manipulation to keep track of the OR of elements in the window.
Let's implement this solution in PHP: 3097. Shortest Subarray With OR at Least K II
minimumSubarrayLength($nums1, $k1) . "\n"; // Output: 1 $nums2 = [2, 1, 8]; $k2 = 10; echo $solution->minimumSubarrayLength($nums2, $k2) . "\n"; // Output: 3 $nums3 = [1, 2]; $k3 = 0; echo $solution->minimumSubarrayLength($nums3, $k3) . "\n"; // Output: 1 ?>Explanation:
minimumSubarrayLength Method:
- Initialize ans to an impossible high value ($n 1).
- Use two pointers l (left) and r (right) to expand and shrink the window.
- Calculate the OR of the subarray as you expand the window with orNum and reduce it with undoOrNum when shrinking.
- Whenever the OR result meets or exceeds k, check if the current window size is smaller than ans.
orNum and undoOrNum Methods:
- orNum method: Adds bits to the cumulative OR by updating the count array. If a bit is newly set in the window (meaning count[i] becomes 1), that bit is added to ors.
- undoOrNum method: Removes bits from the cumulative OR when sliding the window leftward. If a bit is no longer set in any of the numbers in the window (meaning count[i] becomes 0), that bit is removed from ors.
Time Complexity:
- The time complexity is O(n) because each index is added and removed from the deque at most once.
- n is the length of the input array.
4*Time Complexity*:
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Subarray : A subarray is a contiguous non-empty sequence of elements within an array. ↩
The above is the detailed content of Shortest Subarray With OR at Least K II. For more information, please follow other related articles on the PHP Chinese website!