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
Find Shortest Subarray With OR ≥ kInput: nums = [1,2,8,16,4], k = 1012816401234Shortest Valid SubarrayTarget: OR ≥ 10Subarray [8,16]: 8 | 16 = 24 ≥ 10 ✓Length = 2 (minimum possible)Output: 2
Understanding the Visualization
1
Input
Array [1,2,8,16,4] and target k=10
2
Process
Check subarrays: OR of [8,16] = 24 ≥ 10
3
Output
Minimum length is 2
Key Takeaway
🎯 Key Insight: Bitwise OR only increases as we add elements, so we can stop expanding once we reach the target
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