#3878

Count Good Subarrays

Hard
ArrayStackBit ManipulationMonotonic StackHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a monotonic stack to efficiently find the range where each element is the maximum. This reduces the number of checks needed.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a stack to keep track of indices and arrays to store left and right bounds for each element.
  2. 2Step 2: For each element, use the stack to find the nearest greater element to the left and right.
  3. 3Step 3: Calculate the number of good subarrays using the bounds where the element is the maximum.
solution.py20 lines
1def countGoodSubarrays(nums):
2    n = len(nums)
3    left = [0] * n
4    right = [0] * n
5    stack = []
6    for i in range(n):
7        while stack and nums[stack[-1]] < nums[i]:
8            stack.pop()
9        left[i] = stack[-1] if stack else -1
10        stack.append(i)
11    stack.clear()
12    for i in range(n-1, -1, -1):
13        while stack and nums[stack[-1]] <= nums[i]:
14            stack.pop()
15        right[i] = stack[-1] if stack else n
16        stack.append(i)
17    count = 0
18    for i in range(n):
19        count += (i - left[i]) * (right[i] - i)
20    return count

Complexity note: The linear complexity comes from processing each element a constant number of times using the stack.

  • 1A good subarray's OR equals its maximum element.
  • 2Use a monotonic stack to efficiently find bounds.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.