Smallest Subarrays With Maximum Bitwise OR Problem
Description
LeetCode Problem 2411.
You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR.
- In other words, let
B_ijbe the bitwise OR of the subarraynums[i...j]. You need to find the smallest subarray starting ati, such that bitwise OR of this subarray is equal tomax(B_ik)wherei <= k <= n - 1.
The bitwise OR of an array is the bitwise OR of all the numbers in it.
Return an integer array answer of size n where answer[i] is the length of the minimum sized subarray starting at i with maximum bitwise OR.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,0,2,1,3]
Output: [3,3,2,2,1]
Explanation:
The maximum possible bitwise OR starting at any index is 3.
- Starting at index 0, the shortest subarray that yields it is [1,0,2].
- Starting at index 1, the shortest subarray that yields the maximum bitwise OR is [0,2,1].
- Starting at index 2, the shortest subarray that yields the maximum bitwise OR is [2,1].
- Starting at index 3, the shortest subarray that yields the maximum bitwise OR is [1,3].
- Starting at index 4, the shortest subarray that yields the maximum bitwise OR is [3].
Therefore, we return [3,3,2,2,1].
Example 2:
Input: nums = [1,2]
Output: [2,1]
Explanation:
Starting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2.
Starting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1.
Therefore, we return [2,1].
Constraints:
n == nums.length1 <= n <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Reverse Scan
The maximum OR of any suffix starting at i is the OR of every bit that appears anywhere at or after i. So the shortest subarray from i must reach the nearest occurrence of each of those bits.
Scan from right to left and keep f[j], the closest index at or after the current position whose number has bit j set (-1 if none). At index i, update f[j] = i for every bit set in nums[i]. For every other bit with f[j] != -1, the subarray must extend to f[j], so the length is the largest f[j] - i + 1, and at least 1.
Complexity: O(n log m) time, where m is the largest value (about 32 bits per number), and O(log m) extra space.
class Solution:
def smallestSubarrays(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [1] * n
f = [-1] * 32
for i in range(n - 1, -1, -1):
t = 1
for j in range(32):
if (nums[i] >> j) & 1:
f[j] = i
elif f[j] != -1:
t = max(t, f[j] - i + 1)
ans[i] = t
return ans