Number of Subarrays with Bounded Maximum - Problem

Given an integer array nums and two integers left and right, we need to find the number of contiguous non-empty subarrays where the maximum element falls within the range [left, right] (inclusive).

Think of this as finding all possible "windows" in the array where the largest number in that window is neither too small (less than left) nor too large (greater than right).

Example: If we have array [2, 1, 4, 9, 3] with left = 2 and right = 4, we count subarrays like [2], [2, 1], [4], [3], etc., but not [9] or [4, 9] since 9 is too large.

The challenge is to do this efficiently without checking every possible subarray individually!

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [2,1,4,9,3], left = 2, right = 4
โ€บ Output: 3
๐Ÿ’ก Note: Valid subarrays are [2], [4], [3]. Subarrays like [2,1] have max=2 (valid), [1,4] has max=4 (valid), [4,9] has max=9 (invalid), etc. Total count is 3.
example_2.py โ€” All Elements in Range
$ Input: nums = [2,9,2,5,6], left = 2, right = 8
โ€บ Output: 7
๐Ÿ’ก Note: Elements 2,2,5,6 are in range [2,8], only 9 is out of range. Valid subarrays: [2],[2],[5],[6],[2,2],[2,5],[5,6] = 7 subarrays.
example_3.py โ€” Single Element
$ Input: nums = [1], left = 1, right = 1
โ€บ Output: 1
๐Ÿ’ก Note: Only one subarray [1] exists, and its maximum (1) is within range [1,1], so answer is 1.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 0 โ‰ค nums[i] โ‰ค 109
  • 0 โ‰ค left โ‰ค right โ‰ค 109
  • The answer is guaranteed to fit in a 32-bit integer

Visualization

Tap to expand
๐ŸŽฏ Smart Quality Control StrategyProducts: [Quality 2, 1, 4, 9, 3] Range: [2,4]21493Step 1: Count groups with max โ‰ค 4Groups: [2],[1],[4],[3],[2,1],[1,4],[3]Count = 7Step 2: Count groups with max โ‰ค 1Groups: [1]Count = 1Final Answer: 7 - 1 = 6Groups with quality in [2,4]โšก Time: O(n), Space: O(1)
Understanding the Visualization
1
Count groups with quality โ‰ค upper limit
Walk the conveyor belt and count all consecutive groups where no product exceeds the upper quality limit
2
Count groups with quality โ‰ค (lower limit - 1)
Do the same counting but with a threshold one less than our lower quality limit
3
Subtract to get perfect range
The difference gives us exactly the groups with quality in our target range
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking O(nยฒ) subarrays individually, we count valid subarrays mathematically using subtraction: count(max โ‰ค right) - count(max โ‰ค left-1) = count(max โˆˆ [left,right])
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
62.0K Views
Medium Frequency
~25 min Avg. Time
1.8K 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