VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-subarray-such-that-its-bitwise-or-is-at-least-k/

⇱ Smallest subarray such that its bitwise OR is at least k - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest subarray such that its bitwise OR is at least k

Last Updated : 12 May, 2024

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:

  • Initialize:
    • Set ans to the maximum possible length (array size + 1).
    • Set current_OR to 0.
    • Create a bitCount vector to store bit counts (size 32).
    • Set left to 0.
  • Iterate through the array:
    • Update current_OR with the current element's OR value.
    • Update bitCount for the current element's bits.
  • Shrink the window:
    • While current_OR is greater than or equal to k:
    • Update ans with the minimum length if needed.
    • Calculate a new current_OR and update bitCount for the shrunk window.
    • Move left one position to the right.
  • If ans is still the maximum possible length, return -1 (no subarray found).
  • Otherwise, return ans (minimum length).

Below is the implementation of the above approach:


Output
Minimum subarray length with sum >= k: 1

Time Complexity: O(32*N)
Auxiliary Space: O(1)

Comment
Article Tags: