Shortest Subarray With OR at Least K I - Complete Solution Guide
Shortest Subarray With OR at Least K I is LeetCode problem 3095, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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: T
Detailed Explanation
The problem asks you to find the length of the shortest subarray within a given array `nums` such that the bitwise OR of all elements in that subarray is at least `k`. The input is an array of non-negative integers (`nums`) and an integer (`k`). The output is the length of the shortest subarray satisfying the condition, or -1 if no such subarray exists. Subarrays must be non-empty. The constraints limit the array size and element values to relatively small ranges.
Solution Approach
The provided code uses a brute-force approach. It iterates through all possible subarrays of `nums`. For each subarray, it calculates the bitwise OR of its elements. If the OR result is greater than or equal to `k`, it updates the minimum length seen so far. The algorithm then returns the minimum length or -1 if no subarray meets the criteria.
Step-by-Step Algorithm
- Initialize `min_len` to infinity (or a large value).
- Iterate through all possible starting indices `i` of subarrays (outer loop).
- For each starting index `i`, iterate through all possible ending indices `j` (inner loop).
- Calculate the bitwise OR (`current_or`) of elements from `nums[i]` to `nums[j]` (inclusive).
- If `current_or` is greater than or equal to `k`, update `min_len` to the minimum of `min_len` and `(j - i + 1)`.
- After checking all subarrays, return `min_len` if it's less than infinity; otherwise, return -1.
Key Insights
- The problem can be efficiently solved using a sliding window approach, although a brute-force approach is also feasible given the constraints.
- Bitwise OR operations are crucial; understanding their properties (associativity, commutativity) is essential.
- The solution needs to handle the case where no subarray satisfies the condition (returning -1).
Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(1)
Topics
This problem involves: Array, Bit Manipulation, Sliding Window.
Companies
Asked at: Mitsogo.