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.
1using System;
2
3public class ShortestSubarraySolver {
4 public static int ShortestSubarrayWithORAtLeastK(int[] nums, int k) {
5 int left = 0, currOR = 0, minLength = int.MaxValue;
6 for (int right = 0; right < nums.Length; ++right) {
7 currOR |= nums[right];
8 while (currOR >= k && left <= right) {
9 minLength = Math.Min(minLength, right - left + 1);
10 currOR ^= nums[left++];
11 }
12 }
13 return minLength == int.MaxValue ? -1 : minLength;
14 }
15
16 static void Main() {
17 int[] nums = {1, 2, 3};
18 int k = 2;
19 Console.WriteLine(ShortestSubarrayWithORAtLeastK(nums, k)); // Output: 1
20 }
21}
22
This C# solution iteratively applies the OR operation, monitors using XOR to ensure compliance with the condition, and updates the minimum subarray size as necessary. The Math.Min
function assists in minimizing the length.
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.