Number of Subarrays with Bounded Maximum - Problem

Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].

The test cases are generated so that the answer will fit in a 32-bit integer.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,4,9,3], left = 2, right = 3
Output: 3
💡 Note: Valid subarrays are [2], [2,1], and [3]. These have maximums 2, 2, and 3 respectively, all within [2,3]
Example 2 — Larger Range
$ Input: nums = [73,55,36,5,55,14,9,7,72,52], left = 32, right = 69
Output: 22
💡 Note: Multiple subarrays have their maximum element in the range [32,69], including single elements and combinations
Example 3 — Small Array
$ Input: nums = [1,2], left = 1, right = 2
Output: 3
💡 Note: All possible subarrays [1], [2], and [1,2] have maximums within [1,2]

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 0 ≤ nums[i] ≤ 109
  • 0 ≤ left ≤ right ≤ 109

Visualization

Tap to expand
Count Subarrays with Max in [2,3]21493too smalltoo bigtoo bigValid subarrays: [2], [2,1], [3]Max values: 2, 2, 3 (all in range [2,3])Result: 3Count of valid subarrays
Understanding the Visualization
1
Input
Array [2,1,4,9,3] with range [2,3]
2
Process
Find all subarrays with max in [2,3]
3
Output
Count = 3 valid subarrays
Key Takeaway
🎯 Key Insight: Transform the bounded maximum problem into a difference of two 'at most' counting problems for optimal O(n) solution
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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