Taro Logo

Shortest Subarray With OR at Least K I

#9 Most AskedEasy
0 views
Topics:
ArraysSliding WindowsBit Manipulation

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements in the `nums` array, and can they contain negative numbers or zeros?
  2. What is the maximum size (length) of the `nums` array and the possible range of values for `k`?
  3. If multiple subarrays achieve a bitwise OR of at least `k` with the same minimum length, does it matter which one we base our length calculation on?
  4. What should be returned if no subarray has a bitwise OR of at least `k`?
  5. Can the input array `nums` be empty, and how should we handle that edge case?

Brute Force Solution

Approach

To solve this problem using a brute force strategy, we will examine every possible smaller group of numbers that sit right next to each other in the original sequence. For each group, we will combine their values and see if the combined result meets or exceeds the target goal, eventually finding the smallest group that succeeds.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at every single number by itself to see if its own value is already large enough to meet the target.
  2. If none of the individual numbers are large enough on their own, move on to every possible pair of numbers that sit right next to each other.
  3. Combine the values of each pair and check if that combined result meets or exceeds the target goal.
  4. If still no luck, expand the search to every possible group of three numbers sitting next to each other, and check their combined value.
  5. Continue this process by looking at groups of four, five, and even larger groups, always making sure the numbers in the group are right next to each other.
  6. As soon as you find any group whose combined value successfully reaches the target, stop and remember how many numbers were in that group.
  7. Compare the sizes of all the successful groups you found along the way, and declare the smallest group size as your final answer.

Code Implementation

def minimum_subarray_length(number_list, target_value):
    shortest_length = float('inf')
    total_elements = len(number_list)

    # Iterate through all possible starting points for our contiguous subarrays
    for start_index in range(total_elements):
        current_bitwise_or = 0

        # Expand the subarray to the right to accumulate the bitwise OR result
        for end_index in range(start_index, total_elements):
            current_bitwise_or |= number_list[end_index]

            # Check if the accumulated OR meets the target goal for valid evaluation
            if current_bitwise_or >= target_value:
                current_length = (end_index - start_index) + 1
                if current_length < shortest_length:
                    shortest_length = current_length
                break

    # Return the minimum length found, or -1 if no valid subarray exists
    if shortest_length == float('inf'):
        return -1
    return shortest_length

Big(O) Analysis

Time Complexity
O(n²) – The brute force approach examines every possible contiguous subarray by using nested loops to determine the start and end points. With an array of size n, the outer loop selects the starting index while the inner loop expands the ending index to check group sizes ranging from one up to n. Summing the number of subarrays checked for each possible starting position leads to approximately n * (n + 1) / 2 total operations. Simplifying this expression by dropping constant factors and lower-order terms yields a final time complexity of O(n²).
Space Complexity
O(1) – The brute force strategy examines subarrays by using a few primitive integer variables for loop counters, subarray boundaries, and the running bitwise OR total. Because no auxiliary data structures, recursion stack frames, or dynamically sized collections are utilized, the extra memory usage remains constant regardless of the input array size N. Thus, the auxiliary space complexity is strictly O(1).

Optimal Solution

Approach

This solution finds the shortest contiguous subarray whose bitwise OR sum is at least a specified threshold. Since the array length is at most 50, we can evaluate all potential subarrays starting at each index. We expand subarrays until their bitwise OR meets or exceeds the target, updating the minimal length encountered.

Here's how the algorithm would work step-by-step:

  1. Initialize the minimum subarray length to infinity.
  2. Loop over each index in the input array to serve as the start of a subarray.
  3. Accumulate the bitwise OR of elements extending from the start index to the right.
  4. Once the cumulative bitwise OR reaches or exceeds the target value, record the length and break early from the inner loop.
  5. Return the minimum length found, or -1 if no subarray achieves the desired bitwise OR value.

Code Implementation

def minimum_subarray_length(nums: list[int], target_value: int) -> int:
    # Initialize the minimum length with infinity
    min_length = float('inf')
    array_size = len(nums)
    # Iterate through all possible starting points of subarrays
    for start_index in range(array_size):
        current_or = 0
        # Expand the subarray from start_index to the right
        for end_index in range(start_index, array_size):
            current_or |= nums[end_index]
            # Check if the bitwise OR condition meets or exceeds the target
            if current_or >= target_value:
                current_length = end_index - start_index + 1
                min_length = min(min_length, current_length)
                break
    return min_length if min_length != float('inf') else -1

Big(O) Analysis

Time Complexity
O(N^2) – There are nested loops where the outer loop iterates over all starting indices and the inner loop iterates over ending indices up to N. In the worst case, evaluating all pairs takes O(N^2) operations, which is well within constraints for N up to 50.
Space Complexity
O(1) – Only a few auxiliary variables are used to track the running bitwise OR and the minimal length, requiring constant extra space.

Edge Cases

Array of size 1 where the single element is less than k
How to Handle:
The algorithm checks the element, fails to meet the condition, and correctly returns -1.
Array of size 1 where the single element is greater than or equal to k
How to Handle:
The algorithm immediately recognizes the valid condition and returns a length of 1.
No subarray in the entire array has a bitwise OR of at least k
How to Handle:
The algorithm exhausts all possibilities and returns the default failure value of -1.
k equals 0
How to Handle:
Any non-empty subarray has an OR of at least 0, so the algorithm should instantly return the minimum possible length of 1.
Array contains numbers with all bits set to 0
How to Handle:
Zeros do not contribute any set bits to the bitwise OR sum, requiring the algorithm to expand the window until non-zero elements are included.
Multiple overlapping valid subarrays of different lengths
How to Handle:
Using a sliding window or two-pointer approach allows us to track and minimize the length dynamically to find the absolute shortest.
Maximum possible constraint values for array elements and k
How to Handle:
Bitwise operations run in standard integer space, so we must ensure bit manipulations do not exceed standard integer bit-widths.
Extremely large input arrays scaling up to upper constraints
How to Handle:
An optimized O(n) sliding window approach avoids nested loops, ensuring the solution executes well within standard time limits.
0/10 completed