Shortest Subarray With OR at Least K II - Problem

You are given an array nums of non-negative integers and an integer k.

An array is called special if the bitwise OR of all of its elements is at least k.

Return the length of the shortest special non-empty subarray of nums, or return -1 if no special subarray exists.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3], k = 2
Output: 1
💡 Note: The subarray [2] has OR = 2 ≥ 2, and [3] has OR = 3 ≥ 2. Both have length 1, which is minimum.
Example 2 — Need Multiple Elements
$ Input: nums = [2,1,8], k = 10
Output: 3
💡 Note: No single element ≥ 10. [2,1] gives OR = 3 < 10. Need all three: [2,1,8] gives OR = 2|1|8 = 11 ≥ 10.
Example 3 — No Solution
$ Input: nums = [1,2], k = 5
Output: -1
💡 Note: Maximum possible OR is 1|2 = 3, which is less than k = 5. No special subarray exists.

Constraints

  • 1 ≤ nums.length ≤ 2 × 105
  • 0 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 109

Visualization

Tap to expand
Shortest Subarray With OR at Least K II INPUT Array nums: 1 idx 0 2 idx 1 3 idx 2 Binary Values: 01 10 11 Target k: k = 2 Find shortest subarray with OR >= 2 ALGORITHM STEPS 1 Sliding Window Two pointers: left, right 2 Track OR Bits Count bits at each position 3 Expand Right Add nums[right] to OR 4 Shrink Left If OR >= k, try smaller Check each element: [1]: 1 OR = 1 < 2 [2]: 2 OR = 2 >= 2 OK [3]: 3 OR = 3 >= 2 OK FINAL RESULT Shortest special subarray found: 2 Single element [2] OR value = 2 >= k Output: 1 Length = 1 Minimum possible length for OR >= 2 Key Insight: OR operation is monotonic: adding elements can only keep or increase the result. Use sliding window with bit counting to efficiently track OR when shrinking window. Time: O(n * 32) = O(n), Space: O(32) = O(1) for 32-bit integers. TutorialsPoint - Shortest Subarray With OR at Least K II | Optimal Solution
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~25 min Avg. Time
890 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