Shortest Subarray With OR at Least K I - Problem

You're tasked with finding the shortest contiguous subarray within an array of non-negative integers where the bitwise OR of all elements equals or exceeds a given threshold k.

A subarray is considered "special" if when you perform the bitwise OR operation on all its elements, the result is at least k. The bitwise OR operation combines bits using the rule: if either bit is 1, the result is 1.

Your goal: Return the length of the shortest special non-empty subarray, or -1 if no such subarray exists.

Example: For array [2, 1, 8] and k = 10, the subarray [2, 8] has OR value 2 | 8 = 10, which meets our threshold with length 2.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [2, 1, 8], k = 10
โ€บ Output: 3
๐Ÿ’ก Note: The subarray [2, 1, 8] has OR value 2|1|8 = 11, which is >= 10. This is the shortest possible subarray with the required property.
example_2.py โ€” Shorter Subarray
$ Input: nums = [1, 2, 3], k = 2
โ€บ Output: 1
๐Ÿ’ก Note: The subarray [2] has OR value 2, which equals k = 2. Length is 1, which is optimal.
example_3.py โ€” No Valid Subarray
$ Input: nums = [1, 2], k = 5
โ€บ Output: -1
๐Ÿ’ก Note: No subarray has OR value >= 5. The maximum possible OR is 1|2 = 3, which is less than k = 5.

Visualization

Tap to expand
Sliding Window for OR >= k2010100181000k = 10 (1010)WindowStep 1: Single element OR = 2 < 10WindowStep 2: Expand OR = 2|1 = 3 < 10Valid WindowStep 3: Expand OR = 2|1|8 = 11 >= 10 โœ“LRLength = R - L + 1 = 3Key Insight:OR operations are monotonic: adding elements can only increase the result.This property makes sliding window approach optimal for finding minimum length.๐ŸŽฏ Time: O(nร—log(max_value)), Space: O(1)
Understanding the Visualization
1
Initialize Window
Start with empty window, prepare to expand
2
Expand & Calculate
Add elements and calculate OR incrementally
3
Shrink When Valid
When OR >= k, try to reduce window size from left
4
Track Minimum
Always remember the shortest valid window found
Key Takeaway
๐ŸŽฏ Key Insight: OR operations are monotonic, making sliding window perfect for finding the shortest valid subarray efficiently.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n ร— log(max_value))

Each element visited twice, but OR recalculation for shrinking adds log factor

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using pointer variables and OR accumulator

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 50
  • 0 โ‰ค nums[i] โ‰ค 50
  • 0 โ‰ค k โ‰ค 50
  • All array elements are non-negative integers
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
23.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen