Count Subarrays With Fixed Bounds - Problem
Given an integer array
A fixed-bound subarray is a contiguous portion of the array that satisfies both conditions:
⢠The minimum value in the subarray equals
⢠The maximum value in the subarray equals
For example, in array
Your task is to count how many such valid subarrays exist in the given 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
maxKFor 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
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
ā Quadratic Growth
Space Complexity
O(1)
Only using constant extra variables for tracking min, max, and count
ā Linear Space
Constraints
- 2 ⤠nums.length ⤠105
- 1 ⤠nums[i], minK, maxK ⤠106
- minK ⤠maxK (guaranteed)
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code