Shortest Subarray With OR at Least K I - 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: Element 2 by itself has OR = 2 ≥ 2, so minimum length is 1. Element 3 also works with OR = 3 ≥ 2.
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 < 5, so no subarray can achieve OR ≥ 5.

Constraints

  • 1 ≤ nums.length ≤ 50
  • 0 ≤ nums[i] ≤ 50
  • 0 ≤ k ≤ 50

Visualization

Tap to expand
Shortest Subarray With OR at Least K 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 (binary: 10) ALGORITHM STEPS 1 Check each element If nums[i] >= k, return 1 2 Sliding window Expand right, track OR 3 When OR >= k Shrink left, update min 4 Return minimum length Or -1 if none found Execution: i=0: nums[0]=1, 1<2 i=1: nums[1]=2, 2>=2 OK Found! Length = 1 i=2: nums[2]=3, 3>=2 OK FINAL RESULT Shortest special subarray: [2] OR value: 2 2 >= k (2) Also valid: [3] OR = 3 >= 2 Output: 1 OK - Minimum length found Key Insight: Bitwise OR is monotonically increasing: adding more elements can only set more bits. If a single element already satisfies nums[i] >= k, that's the shortest possible (length 1). Use sliding window with bit counting to efficiently shrink from left while maintaining OR. TutorialsPoint - Shortest Subarray With OR at Least K I | Optimal Solution
Asked in
Google 25 Amazon 18 Microsoft 15
12.9K Views
Medium Frequency
~15 min Avg. Time
542 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