Leetcode 3095. Shortest Subarray With OR at Least K I
Given an array of non-negative integers nums
and an integer K
, you need to find the shortest subarray with a bitwise OR sum of at least K
. If there isn’t one, return -1
.
K
be greater than the sum of the bitwise OR of the entire array?
K
to potentially find a shorter subarray.public class Solution {
public int shortestSubarrayWithORAtLeastK(int[] nums, int K) {
// Edge case
if (nums == null || nums.length == 0) return -1;
int n = nums.length;
int minLength = Integer.MAX_VALUE;
int currentOR = 0;
int left = 0;
// Iterate over the array with the right pointer
for (int right = 0; right < n; right++) {
currentOR |= nums[right];
// Contract the window while the condition is met
while (left <= right && currentOR >= K) {
minLength = Math.min(minLength, right - left + 1);
currentOR &= ~nums[left];
left++;
}
}
return minLength == Integer.MAX_VALUE ? -1 : minLength;
}
}
// Example usage
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 3, 4, 5};
int K = 6;
System.out.println("Shortest subarray length: " + solution.shortestSubarrayWithORAtLeastK(nums, K)); // Output: 2
}
}
This solution iteratively adjusts a sliding window over the array and dynamically maintains the bitwise OR, making it efficient and effective for the problem at hand.
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?