Sponsored
Sponsored
The sliding window approach allows us to efficiently consider subarrays by expanding and contracting the window size while checking the OR condition. We start by iterating over the array using two pointers that track the start and end of the current window. The objective is to maintain a OR condition that satisfies the requirement of being at least k, while minimizing the window size.
Time Complexity: O(n), as each element is processed at most twice.
Space Complexity: O(1), since no additional data structures proportional to input size are used.
1public class ShortestSubarray {
2 public static int shortestSubarrayWithORAtLeastK(int[] nums, int k) {
3 int left = 0, currOR = 0, minLength = Integer.MAX_VALUE;
4 for (int right = 0; right < nums.length; ++right) {
5 currOR |= nums[right];
6 while (currOR >= k && left <= right) {
7 minLength = Math.min(minLength, right - left + 1);
8 currOR ^= nums[left++];
9 }
10 }
11 return minLength == Integer.MAX_VALUE ? -1 : minLength;
12 }
13
14 public static void main(String[] args) {
15 int[] nums = {1, 2, 3};
16 int k = 2;
17 System.out.println(shortestSubarrayWithORAtLeastK(nums, k)); // Output: 1
18 }
19}
20
This Java solution employs a rolling OR to keep extending the subarray as needed, applying XOR to reduce the length when possible while still satisfying the OR condition. Java's Math.min
function is used for maintaining the minimum size of the subarray.
The brute force approach involves examining all possible non-empty subarrays. Although this method is not efficient for large inputs, it is a straightforward solution that guarantees finding the result by evaluating each subarray's OR value and checking against the condition.
Time Complexity: O(n^2), as it checks each subarray.
Space Complexity: O(1), with basic indexing variables used.
1
In JavaScript, this brute force technique checks all sets of subarrays for every potential beginning, recording and updating the minimal length of those meeting the OR condition. Traditional nested loops help execute this evaluation straightforwardly.