Smallest Subarrays With Maximum Bitwise OR — LeetCode 2411 Python Solution

MediumBit ManipulationArrayBinary SearchSliding Window
Problem
#2411
Reading time
3 min

The problem

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.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log m), where n is the length of the array nums, and m is the maximum value in the array nums
SpaceO(1) to O(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2411. Smallest Subarrays With Maximum Bitwise OR is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2411. Smallest Subarrays With Maximum Bitwise OR?
LeetCode 2411. Smallest Subarrays With Maximum Bitwise OR is rated Medium on LeetCode.
What topics does LeetCode 2411. Smallest Subarrays With Maximum Bitwise OR cover?
LeetCode 2411. Smallest Subarrays With Maximum Bitwise OR is tagged Bit Manipulation, Array, Binary Search and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview