#3097

Shortest Subarray With OR at Least K II

Medium
ArrayBit ManipulationSliding WindowSliding WindowDeque
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a sliding window technique to maintain a dynamic subarray and efficiently compute the bitwise OR. This reduces the time complexity significantly by avoiding redundant calculations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a deque to store indices and a variable for the current OR value.
  2. 2Step 2: Iterate through the array, updating the current OR value with each element.
  3. 3Step 3: While the current OR is at least k, update the minimum length and remove elements from the front of the deque.
  4. 4Step 4: Add the current index to the deque.
  5. 5Step 5: Return the minimum length found or -1 if no valid subarray exists.
solution.py15 lines
1# Full working Python code
2from collections import deque
3
4def shortestSubarray(nums, k):
5    n = len(nums)
6    min_length = float('inf')
7    current_or = 0
8    dq = deque()
9    for i in range(n):
10        current_or |= nums[i]
11        dq.append(i)
12        while current_or >= k:
13            min_length = min(min_length, dq[-1] - dq[0] + 1)
14            current_or ^= nums[dq.popleft()]  # Remove the leftmost element
15    return min_length if min_length != float('inf') else -1

Complexity note: This complexity is achieved because we only traverse the array once, and the deque operations are amortized constant time.

  • 1Bitwise OR accumulates bits, never unsetting them.
  • 2Using a sliding window allows for efficient tracking of valid subarrays.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.