LeetCode 3097: Shortest Subarray With OR at Least K II Solution

Master LeetCode problem 3097 (Shortest Subarray With OR at Least K II), a medium 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.

3097. Shortest Subarray With OR at Least K II

Problem Explanation

Explanation

To solve this problem, we can use a deque (double-ended queue) to maintain a monotonically increasing prefix sum array. We iterate through the input array and keep track of the prefix sum and its corresponding index in the deque. Whenever the current prefix sum is greater than or equal to k, we update the result with the minimum subarray length and remove elements from the front of the deque until the prefix sum is less than k. This helps in finding the shortest special subarray.

Time Complexity

The time complexity of this approach is O(n), where n is the number of elements in the input array.

Space Complexity

The space complexity of this approach is O(n) for the deque.

Solution Code

class Solution {
    public int shortestSubarray(int[] nums, int k) {
        Deque<Integer> deque = new LinkedList<>();
        int n = nums.length;
        int[] prefixSum = new int[n + 1];
        int result = Integer.MAX_VALUE;

        for (int i = 0; i < n; i++) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
        }

        for (int i = 0; i <= n; i++) {
            while (!deque.isEmpty() && prefixSum[i] - prefixSum[deque.peekFirst()] >= k) {
                result = Math.min(result, i - deque.pollFirst());
            }
            while (!deque.isEmpty() && prefixSum[i] <= prefixSum[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
        }

        return result == Integer.MAX_VALUE ? -1 : result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3097 (Shortest Subarray With OR at Least K II)?

This page provides optimized solutions for LeetCode problem 3097 (Shortest Subarray With OR at Least K II) 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 3097 (Shortest Subarray With OR at Least K II)?

The time complexity for LeetCode 3097 (Shortest Subarray With OR at Least K II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3097 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3097 in Java, C++, or Python.

Back to LeetCode Solutions