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.
1function shortestSubarrayWithORAtLeastK(nums, k) {
2 let left = 0, currOR = 0, minLength = Infinity;
3 for (let right = 0; right < nums.length; ++right) {
4 currOR |= nums[right];
5 while (currOR >= k && left <= right) {
6 minLength = Math.min(minLength, right - left + 1);
7 currOR ^= nums[left++];
8 }
9 }
10 return minLength === Infinity ? -1 : minLength;
11}
12
13let nums = [1, 2, 3], k = 2;
14console.log(shortestSubarrayWithORAtLeastK(nums, k)); // Output: 1
15
The JavaScript solution directly leverages its dynamic typing to apply similar logic as other languages, using bitwise operations to reach the condition checking. The Math.min
function is utilized for calculating the shortest span.
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.