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
Number of Subarrays with Bounded Maximum INPUT nums array: 2 i=0 1 i=1 4 i=2 9 i=3 3 i=4 Range: [left, right] [2, 3] In range [2,3] Above range (>3) Below range (<2) Find subarrays where max is in [2, 3] [2], [2,1], [3] ALGORITHM STEPS 1 Track Positions j = last idx > right k = last idx in [left,right] 2 For each i: Update j if nums[i] > right Update k if nums[i] in range 3 Contribution Add max(0, k - j) to result 4 Sum All Return total count Iteration Trace i nums[i] j k k-j cnt 0 2 -1 0 1 1 1 1 -1 0 1 2 2 4 2 0 0 2 3 9 3 0 0 2 4 3 3 4 1 3 FINAL RESULT Valid Subarrays Found: 1. [2] max=2, in [2,3] OK 2. [2,1] max=2, in [2,3] OK 3. [3] max=3, in [2,3] OK Invalid examples: [4] max=4 > 3 [2,1,4] max=4 > 3 [1] max=1 < 2 Output: 3 Key Insight: The contribution technique counts subarrays ending at each index i. Track j (last position where element > right) and k (last position where element is in [left,right]). For each i, subarrays from j+1 to k ending at i are valid. Time: O(n), Space: O(1). TutorialsPoint - Number of Subarrays with Bounded Maximum | Counting with Contribution Technique
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