![]() |
VOOZH | about |
Given an array arr[] of non-negative integers and an integer k. The task is to find the smallest non-empty subarray of arr[] such that the bitwise OR of all of its elements is at least k, or return -1 if no subarray exists.
Example:
Input: arr = {1,2,3}, k = 2
Output: 1
Explanation: The subarray {3} has OR value of 3. Hence, we return 1.Input: arr = {2,1,8}, k = 10
Output: 3
Explanation: The subarray {2,1,8} has OR value of 11. Hence, we return 3.Input: arr = {1,2}, k = 0
Output: 1
Explanation: The subarray {1} has OR value of 1. Hence, we return 1.
Approach:
We can use sliding window approach to solve this problem. When the running bitwise OR becomes greater than k, we will update our left pointer (shrink the sliding window) until the OR is less than k, and then update our answer accordingly.
The main concept involves calculating the new OR when we shrink the window.
- Initially, we store the count of set bits at any ith position for arr[i].
- When the OR becomes greater than or equal to k, we run a while loop until the OR is less than k.
- Within the while loop, we subtract the set bits in arr[l] from bitsCount and calculate the new OR value from the set bits in bitsCount.
- This can be achieved by either unsetting the jth bit in the OR if bitsCount[j] equals 0, or by using a new variable newcurrent_OR and setting the jth bit if bitsCount[j] is greater than 0.
Step-by-step approach:
Below is the implementation of the above approach:
Minimum subarray length with sum >= k: 1
Time Complexity: O(32*N)
Auxiliary Space: O(1)