Smallest Subarrays With Maximum Bitwise OR - 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.

In other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find the smallest subarray starting at i, such that bitwise OR of this subarray is equal to max(Bik) where i ≤ 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,0,3,5]
Output: [3,3,2,1]
💡 Note: Starting at index 0: maximum OR is 1|0|3|5=7, minimum length is 3 (need [1,0,3] to get OR=3, then add 5 to get 7). Starting at index 1: need [0,3,5] for maximum OR=7. Starting at index 2: need [3,5] for OR=7. Starting at index 3: only [5] gives OR=5.
Example 2 — Single Element
$ Input: nums = [8]
Output: [1]
💡 Note: Only one element, so the minimum subarray starting at index 0 has length 1 with OR=8.
Example 3 — All Same Values
$ Input: nums = [2,2,2]
Output: [1,1,1]
💡 Note: All elements are the same, so from each position, a single element achieves the maximum OR of 2.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 108

Visualization

Tap to expand
Smallest Subarrays With Maximum Bitwise OR1035index 0index 1index 2index 3From index 0: need length 3From index 1: need length 3From index 2: need length 23321Output: [3,3,2,1]
Understanding the Visualization
1
Input Array
Array [1,0,3,5] with bitwise OR operations
2
Find Max OR
Calculate maximum possible OR from each starting position
3
Find Min Length
Determine shortest subarray achieving maximum OR
Key Takeaway
🎯 Key Insight: Bitwise OR only increases or stays same, so we can efficiently find when maximum is achieved
Asked in
Microsoft 35 Google 28 Amazon 22
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen