LeetCode 3095: Shortest Subarray With OR at Least K I Solution
Master LeetCode problem 3095 (Shortest Subarray With OR at Least K I), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3095. Shortest Subarray With OR at Least K I
Problem Explanation
Explanation
To solve this problem, we can use a sliding window approach. We will iterate over the array and keep expanding the window until the OR value of the elements in the window is at least k. If the OR value is less than k, we will shrink the window from the left side. We will maintain a variable to keep track of the minimum length of the special subarray found so far.
At each step, we will update the minimum length of the special subarray if a new special subarray with shorter length is found.
Time Complexity: O(n), where n is the number of elements in the input array nums. Space Complexity: O(1)
Solution Code
class Solution {
public int shortestSubarray(int[] nums, int k) {
int n = nums.length;
int minLen = n + 1;
int left = 0;
int right = 0;
int orValue = 0;
while (right < n) {
orValue |= nums[right];
while (orValue >= k) {
minLen = Math.min(minLen, right - left + 1);
orValue &= ~nums[left];
left++;
}
right++;
}
return minLen == n + 1 ? -1 : minLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3095 (Shortest Subarray With OR at Least K I)?
This page provides optimized solutions for LeetCode problem 3095 (Shortest Subarray With OR at Least K I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3095 (Shortest Subarray With OR at Least K I)?
The time complexity for LeetCode 3095 (Shortest Subarray With OR at Least K I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3095 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3095 in Java, C++, or Python.