Count Subarrays With Fixed Bounds - Problem
Given an integer array nums and two integers minK and maxK, you need to find the number of fixed-bound subarrays.

A fixed-bound subarray is a contiguous portion of the array that satisfies both conditions:
• The minimum value in the subarray equals minK
• The maximum value in the subarray equals maxK

For example, in array [1, 3, 5, 2, 7, 5] with minK = 1 and maxK = 5, the subarray [1, 3, 5] is valid because its minimum is 1 and maximum is 5. However, [3, 5, 2] is not valid because its minimum is 2, not 1.

Your task is to count how many such valid subarrays exist in the given array.

Input & Output

example_1.py — Basic Case
$ Input: nums = [1, 3, 5, 2, 7, 5], minK = 1, maxK = 5
› Output: 2
šŸ’” Note: The valid subarrays are [1,3,5] and [1,3,5,2]. Both have minimum 1 and maximum 5.
example_2.py — Single Element
$ Input: nums = [1, 1, 1, 1], minK = 1, maxK = 1
› Output: 10
šŸ’” Note: All possible subarrays have min=1 and max=1. For array of length 4, there are 4+3+2+1 = 10 subarrays total.
example_3.py — No Valid Subarrays
$ Input: nums = [1, 2, 3], minK = 2, maxK = 4
› Output: 0
šŸ’” Note: No subarray has maximum value 4, so no valid subarrays exist.

Visualization

Tap to expand
Temperature Monitoring SystemDaysTemperature1°3°5°2°8°5°Valid Period: Min=1°, Max=5°LegendMin temp (1°)Valid tempInvalid tempTarget: Min=1°, Max=5°
Understanding the Visualization
1
Track Key Days
Remember the last day we saw the exact min temp, max temp, and any invalid temp
2
Slide Through Time
For each day, update our tracking pointers based on the current temperature
3
Count Valid Periods
Calculate how many valid periods can end on this day
4
Add to Total
Add the count of valid periods to our running total
Key Takeaway
šŸŽÆ Key Insight: By tracking the last positions of our target values and boundary violations, we can efficiently count all valid ranges without checking every possible subarray combination.

Time & Space Complexity

Time Complexity
ā±ļø
O(n³)

Three nested loops: O(n²) for all subarray pairs, O(n) to find min/max of each subarray

n
2n
⚠ Quadratic Growth
Space Complexity
O(1)

Only using constant extra variables for tracking min, max, and count

n
2n
āœ“ Linear Space

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i], minK, maxK ≤ 106
  • minK ≤ maxK (guaranteed)
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
28.4K Views
High Frequency
~25 min Avg. Time
1.3K 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