#2411

Smallest Subarrays With Maximum Bitwise OR

Medium
ArrayBinary SearchBit ManipulationSliding WindowSliding WindowBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a sliding window technique to efficiently find the smallest subarray with the maximum bitwise OR. By tracking the maximum OR and the last seen index of each bit, we can quickly determine the required lengths.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array answer to store results and a variable maxOR to track the maximum bitwise OR.
  2. 2Step 2: Iterate through the array from the end to the beginning, updating maxOR with the current element's OR.
  3. 3Step 3: For each bit in maxOR, find the last index where that bit was set and calculate the length of the subarray from the current index to that last index.
solution.py13 lines
1def smallestSubarrays(nums):
2    n = len(nums)
3    answer = [0] * n
4    maxOR = 0
5    lastIndex = [-1] * 32
6    for i in range(n - 1, -1, -1):
7        maxOR |= nums[i]
8        answer[i] = n
9        for b in range(32):
10            if (maxOR >> b) & 1:
11                lastIndex[b] = i
12                answer[i] = min(answer[i], lastIndex[b] - i + 1)
13    return answer

Complexity note: The time complexity is O(n) because we traverse the array once and check each bit position (constant time). The space complexity is O(n) due to the answer array.

  • 1Understanding bitwise operations is crucial for this problem.
  • 2Using a sliding window can significantly reduce the time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.