Leetcode 3095. Shortest Subarray With OR at Least K I
On Interviewbit, you have been given a problem where you need to find the shortest subarray from a given array such that the bitwise OR of the elements of this subarray is at least a given integer K.
Formally, given an array A of N non-negative integers and an integer K, you need to find the length of the shortest subarray such that the bitwise OR of all elements in that subarray is greater than or equal to K. If no such subarray exists, return -1.
N, elements of A, and K?K?integer type) of the shortest subarray, or some additional information?1 <= N <= 10^50 <= A[i], K <= 10^9K.#include <iostream>
#include <vector>
#include <climits>
using namespace std;
int shortestSubarrayWithORAtLeastK(const vector<int>& A, int K) {
int n = A.size();
int left = 0, right = 0;
int current_or = 0;
int min_length = INT_MAX;
while (right < n) {
// Extend the slide window to the right
current_or |= A[right];
// While current_or is at least K, try to shrink the window from the left
while (left <= right && current_or >= K) {
min_length = min(min_length, right - left + 1);
current_or &= ~A[left]; // Remove the effect of A[left] from current_or
left++;
}
// Increment right pointer to extend the window
right++;
}
return (min_length == INT_MAX) ? -1 : min_length;
}
int main() {
vector<int> A = {1, 2, 4, 8};
int K = 7;
int result = shortestSubarrayWithORAtLeastK(A, K);
cout << "The length of the shortest subarray: " << result << endl;
return 0;
}
left and right, both set to the beginning of the array.current_or to store the OR value of the current subarray.min_length to keep track of the smallest window length found.right to extend the window, updating the OR value by including A[right].current_or reaches or exceeds K, determine if the current window is the smallest by comparing its length with min_length.left to shrink the window from the left. While doing this, exclude A[left] from the OR calculation by using bitwise operations.min_length remains unchanged and we return -1, otherwise return the smallest length found.right pointer and once by the left pointer).This should provide an efficient solution to the problem statement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?