Skip to content
LEETFLIX

Smallest Subarrays With Maximum Bitwise OR

Solve on LeetCode

Medium · binary search solution for Smallest Subarrays With Maximum Bitwise OR. Python, Go, and a step-by-step animation.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 2411. Smallest Subarrays With Maximum Bitwise OR. The copyrighted prompt is on LeetCode. This page is a working binary search solution for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[-1, 0, 3, 5, 9, 12]
target =
9

Output

4

9 sits at index 4. Each step throws away half the range.

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Smallest Subarrays With Maximum Bitwise OR — binary search

Halve the sorted range until the target is found or the range collapses. Built for LeetCode 2411. Smallest Subarrays With Maximum Bitwise OR.

Because the slice is sorted, comparing nums[mid] to target tells you which half can be thrown away. That is the whole algorithm.

Algorithm

  1. While lo <= hi, pick mid.
  2. Equal → return mid. Too small → search right. Too big → search left.
  3. Empty range → not found (-1).
Time
O(log n)
Space
O(1)
Solution.py
class Solution:    def smallestSubarraysWithMaximumBitwiseOr(self, nums: list[int], target: int) -> int:        lo, hi = 0, len(nums) - 1        while lo <= hi:            mid = (lo + hi) // 2            if nums[mid] == target:                return mid            if nums[mid] < target:                lo = mid + 1            else:                hi = mid - 1        return -1
Watch this run

03

Interactive walkthrough

Playing “Smallest Subarrays With Maximum Bitwise OR — binary search”. Edit the input, hit Run, then scrub.

Approach: Smallest Subarrays With Maximum Bitwise OR — binary search

Loading animation…