Magicsheet logo

Smallest Subarrays With Maximum Bitwise OR

Medium
25%
Updated 8/1/2025

Smallest Subarrays With Maximum Bitwise OR

What is this problem about?

The "Smallest Subarrays With Maximum Bitwise OR" interview question asks you to find, for each index i, the length of the shortest subarray starting at i that achieves the maximum possible bitwise OR value for any subarray starting at i. This "Smallest Subarrays With Maximum Bitwise OR coding problem" requires you to track when each bit is "first seen" as you move through the array.

Why is this asked in interviews?

Microsoft and Meta ask this to test your understanding of bitwise operations and efficient array processing. It requires a clever way to avoid the O(N^2) brute-force check. It evaluates your ability to maintain a small amount of state (the last seen position of each of the 32 bits) and use it to solve a range query problem.

Algorithmic pattern used

This follows the "Bit Manipulation and Sliding Window (or Greedy) interview pattern".

  1. The maximum possible bitwise OR for a subarray starting at i is the OR of all elements from nums[i] to the end of the array.
  2. To find the shortest subarray that reaches this value, you only need to find the closest index j >= i that sets all the bits that are ever set in the remainder of the array.
  3. Iterate the array from right to left.
  4. Maintain an array last_seen[32] which stores the last index where the k-th bit was set.
  5. For each index i:
    • Update last_seen with the bits of nums[i].
    • The end of your shortest subarray is max(last_seen[k]) for all bits k that are set in the full OR suffix.
    • Length is max_index - i + 1.

Example explanation

Array: [1, 0, 2, 1, 3]

  1. Suffix ORs: [3, 3, 3, 3, 3] (since the last element 3 has both bits 0 and 1 set).
  2. Right to left:
    • Index 4 (3): last_seen = {0:4, 1:4}. Max index = 4. Length = 1.
    • Index 3 (1): last_seen = {0:3, 1:4}. Max index = 4. Length = 2.
    • Index 2 (2): last_seen = {0:3, 1:2}. Max index = 3. Length = 2.
    • Index 1 (0): last_seen = {0:3, 1:2}. Max index = 3. Length = 3.
    • Index 0 (1): last_seen = {0:0, 1:2}. Max index = 2. Length = 3. Result: [3, 3, 2, 2, 1].

Common mistakes candidates make

A common mistake is trying to use a sliding window with two pointers, which doesn't work well with OR because removing an element doesn't "unset" bits easily. Another error is not iterating backwards, which is much more efficient for "future" bit lookups. Candidates also often forget to handle the case where the current number already contains all the bits (length 1).

Interview preparation tip

Bitwise OR is monotonic—as you add more numbers, the OR value can only stay the same or increase. This "Smallest Subarrays With Maximum Bitwise OR interview question" leverages that property to find the minimal set of elements needed to "hit" every available bit.

Similar Questions