Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 2411: Smallest Subarrays With Maximum Bitwise OR

LeetCode 2411 Solution Explanation

Explanation

To solve this problem, we can iterate over the input array and maintain a sliding window. We will keep track of the maximum value encountered so far and its position. For each index, we will determine the smallest subarray starting at that index that produces the maximum bitwise OR. We will use a deque to store the indices of elements in decreasing order of their values.

  1. Initialize an empty deque and an answer array of size n.
  2. Iterate over the array nums.
  3. For each index i, remove indices from the front of the deque that are not relevant anymore (out of the sliding window or smaller values).
  4. While the deque is not empty and the current element is greater than the element at the back of the deque, remove the back element.
  5. Add the current index to the back of the deque.
  6. Calculate the minimum subarray length for the maximum OR based on the current element and the element at the front of the deque.
  7. Update the answer array with this minimum length.
  8. Repeat steps 2-7 for all indices.
  9. Return the answer array.

Time Complexity: O(n) where n is the number of elements in the input array nums. Space Complexity: O(n) for the deque and answer array.

LeetCode 2411 Solutions in Java, C++, Python

class Solution {
    public int[] minSubarray(int[] nums) {
        int n = nums.length;
        Deque<Integer> deque = new ArrayDeque<>();
        int[] answer = new int[n];

        for (int i = 0; i < n; i++) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);

            while (deque.peekFirst() < i - answer[i]) {
                deque.pollFirst();
            }

            answer[i] = i - deque.peekFirst() + 1;
        }

        return answer;
    }
}

Interactive Code Editor for LeetCode 2411

Improve Your LeetCode 2411 Solution

Use the editor below to refine the provided solution for LeetCode 2411. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems