Skip to main content

Shortest Subarray With OR at Least K I - Solution & Explanation

EasyArrayBit ManipulationSliding Window24 min readAsked at: Mitsogo
Practice this problem

Problem Statement

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.

 

Example 1:

Input: nums = [1,2,3], k = 2

Output: 1

Explanation:

The subarray [3] has OR value of 3. Hence, we return 1.

Note that [2] is also a special subarray.

Example 2:

Input: nums = [2,1,8], k = 10

Output: 3

Explanation:

The subarray [2,1,8] has OR value of 11. Hence, we return 3.

Example 3:

Input: nums = [1,2], k = 0

Output: 1

Explanation:

The subarray [1] has OR value of 1. Hence, we return 1.

 

Constraints:

  • 1 <= nums.length <= 50
  • 0 <= nums[i] <= 50
  • 0 <= k < 64

Approach Overview

Problem Overview: You are given an integer array nums and a value k. The task is to find the length of the shortest non-empty subarray whose bitwise OR is greater than or equal to k. If no such subarray exists, return -1. The challenge comes from the behavior of the bitwise OR operation: once a bit becomes 1, it stays 1 when more elements are added.

Approach 1: Brute Force Enumeration (O(n² * 32) time, O(1) space)

Start every subarray from index i and expand the end pointer j one element at a time. Maintain a running OR value as you extend the subarray using current_or |= nums[j]. After each expansion, check whether current_or >= k. Once the condition is satisfied, update the minimum length and stop extending that start index because any longer subarray will only increase the length. The complexity becomes O(n²) in the worst case, with a constant factor related to bit operations (up to 32 bits for integers). This approach is simple and good for understanding how OR accumulates across a range.

Approach 2: Sliding Window with Bit Counters (O(n * 32) time, O(32) space)

The optimal solution uses a sliding window combined with bit manipulation. The window expands with a right pointer and shrinks with a left pointer. The key difficulty is that removing an element from a window does not directly undo the OR operation. To handle this, maintain an array of size 32 where each index counts how many numbers in the current window contribute that bit.

When you add a number, iterate through its bits and increment the corresponding counters. Reconstruct the current OR value by checking which bit counters are non-zero. If the OR becomes at least k, attempt to shrink the window from the left while maintaining the condition. When removing a number, decrement its bit counters and recompute the OR accordingly. Each element enters and leaves the window once, and each update processes up to 32 bits, resulting in O(n * 32) time and O(32) extra space.

This approach works well because the OR value only depends on whether at least one element contributes a bit. Tracking frequencies allows the window to both grow and shrink efficiently while preserving correctness.

Recommended for interviews: Start by explaining the brute force enumeration to demonstrate understanding of how bitwise OR accumulates across subarrays. Then move to the optimized sliding window solution. Interviewers typically expect the O(n * 32) approach because it combines array traversal, two pointers, and bit tracking to efficiently maintain the OR value while shrinking the window.

Approach 1: Brute Force Approach

The brute force approach explores all possible subarrays, calculates the OR value of each subarray, and keeps track of the shortest one that meets the condition, where the OR value is at least k.

For each subarray, traverse from the start until the end of the subarray, compute the OR value step-by-step, and compare it with k. Update the shortest length whenever you find a valid subarray.

This C code iterates over all possible subarrays using two nested loops. It calculates the OR of elements from the starting point to the current endpoint and checks if the resultant OR is at least k. The minimal length for the satisfying subarrays is stored, updating only when a valid subarray is found.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2) - All pairs of start and end indices are traversed for OR calculation.
Space Complexity: O(1) - No additional space is required besides input handling.

Try this approach in the editor →

Approach 2: Optimized Sliding Window Approach

Using a sliding window mechanism helps to efficiently manage subarrays. The core idea is to apply a dynamic window, expanding until achieving a valid OR value, and then gradually shrinking to find the minimal length subarray.

This method allows efficient optimizations by avoiding redundant recalculations and systematically reducing excessive subarray spans, simplifying the process compared to the exhaustive search.

This C code employs a sliding window approach. Two pointers (start, end) are used to manage a dynamic window. The orValue is calculated iteratively while managing the window size to ensure it's minimal. When the minimal OR condition is met, the start position moves rightward to shrink the window, optimizing operations.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) - Each element is processed at most twice due to the sliding window strategy.
Space Complexity: O(1) - Only pointers and basic elements/constants used outside sequence storage.

Try this approach in the editor →

Approach 3: Two Pointers + Counting

We can observe that if we fix the left endpoint of the subarray, as the right endpoint moves to the right, the bitwise OR value of the subarray will only increase, not decrease. Therefore, we can use the double pointers method to maintain a subarray that meets the conditions.

Specifically, we use two pointers i and j to represent the left and right endpoints of the subarray, respectively. Initially, both pointers are at the first element of the array. We use a variable s to represent the bitwise OR value of the subarray, and initially, the value of s is 0. We also need to maintain an array cnt of length 32, which represents the occurrence times of each bit in the binary representation of each element in the subarray.

In each step, we move j to the right by one position, and update s and cnt. If the value of s is greater than or equal to k, we continuously update the minimum length of the subarray and move i to the right by one position until the value of s is less than k. In this process, we also need to update s and cnt.

Finally, we return the minimum length. If there is no subarray that meets the conditions, we return -1.

The time complexity is O(n times log M) and the space complexity is O(log M), where n and M are the length of the array and the maximum value of the elements in the array, respectively.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Brute Force Approach

Time Complexity: O(n^2) - All pairs of start and end indices are traversed for OR calculation.
Space Complexity: O(1) - No additional space is required besides input handling.

Optimized Sliding Window Approach

Time Complexity: O(n) - Each element is processed at most twice due to the sliding window strategy.
Space Complexity: O(1) - Only pointers and basic elements/constants used outside sequence storage.

Two Pointers + Counting

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subarray ExpansionO(n² * 32)O(1)Good for understanding the OR accumulation behavior or when input size is small
Sliding Window with Bit CountersO(n * 32)O(32)Optimal for large arrays; maintains OR dynamically while shrinking the window

Video Solution

3095. and 3097. Shortest Subarray With OR at Least K I and II || Leetcode || Biweekly contest 127Ashish Kumar731 views views

Watch 4 more video solutions →

Frequently Asked Questions

Is Shortest Subarray With OR at Least K I easy or hard?
The problem is labeled Easy but can feel closer to Medium if you have not handled sliding windows with bit manipulation before. The brute force approach is straightforward, while the optimized method requires tracking bit contributions to correctly update the OR when shrinking the window.
Shortest Subarray With OR at Least K I Python/Java solution
Most implementations use a sliding window and a 32-length bit counter array. Python, Java, C++, and C# solutions iterate through bits using shifts like (num >> bit) & 1 to update counters and rebuild the OR when shrinking the window.
How to solve Shortest Subarray With OR at Least K I in O(n)?
Use a sliding window with bit counting. Track how many numbers in the window contribute to each of the 32 bit positions. When the window expands, update bit counts and recompute the OR. When the OR is at least k, move the left pointer to minimize the window while updating bit counters. Each element enters and exits the window once, resulting in linear scanning with a small constant factor.
What is the best approach for Shortest Subarray With OR at Least K I?
The most efficient approach uses a sliding window combined with bit counters. Maintain a frequency array for the 32 bits of integers and track which bits are active in the current window. Expand the window until the OR value reaches at least k, then shrink it from the left while preserving the condition. This achieves O(n * 32) time and O(32) space.
Is Shortest Subarray With OR at Least K I asked at Google/Amazon/Meta?
Bit manipulation combined with sliding window techniques frequently appears in interviews at companies like Amazon, Google, and Meta. Variants of subarray OR or AND problems are common because they test understanding of bit operations and two-pointer optimization.
What data structure is used in Shortest Subarray With OR at Least K I?
The optimized solution primarily uses an array of size 32 to count how many numbers contribute to each bit position. This structure allows efficient updates when elements enter or leave the sliding window and helps reconstruct the current OR value.
What is the time complexity of Shortest Subarray With OR at Least K I?
The brute force method runs in O(n² * 32) time because every subarray may be explored while updating the OR value. The optimized sliding window solution processes each element once while updating up to 32 bits, giving O(n * 32) time complexity with constant extra space.

Ready to solve this problem?

Practice Shortest Subarray With OR at Least K I with our built-in code editor and test cases.

Practice on FleetCode