Leetcode Problem 2411. Smallest Subarrays With Maximum Bitwise OR

2411. Smallest Subarrays With Maximum Bitwise OR

Leetcode Solutions

Bitwise Last Index Tracking

  1. Initialize an array last of size 30 (since the maximum number in nums can be up to 2^30) to store the last index at which each bit is set.
  2. Iterate through the nums array in reverse, updating the last array for each bit that is set in the current number.
  3. For each index i, find the maximum value in the last array, which represents the farthest index we need to include to get the maximum bitwise OR.
  4. The length of the smallest subarray with the maximum bitwise OR starting at index i is the difference between the maximum value in the last array and i, plus one.
  5. Store this length in the result array.
  6. Return the result array after the iteration is complete.
UML Thumbnail

Brute Force with Bitwise OR Optimization

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...