2444. Count Subarrays With Fixed Bounds - Detailed Explanation
Problem Statement
Description:
You are given an integer array nums and two integers minK and maxK. A fixed-bound subarray of nums is a contiguous subarray that satisfies the following conditions:
- The minimum value in the subarray is equal to
minK. - The maximum value in the subarray is equal to
maxK. - Every element in the subarray lies between
minKandmaxK(inclusive).
Return the number of fixed-bound subarrays.
Examples:
-
Example 1:
- Input:
nums = [1, 3, 5, 2, 7, 5],minK = 1,maxK = 5 - Output:
2 - Explanation:
The valid subarrays are:[1, 3, 5][1, 3, 5, 2]
Other subarrays either do not contain both1and5or contain elements outside the range[1, 5].
- Input:
-
Example 2:
- Input:
nums = [1, 1, 1, 1],minK = 1,maxK = 1 - Output:
10 - Explanation:
SinceminKandmaxKare both1, every subarray (and there are 10 total in an array of length 4) is valid.
- Input:
-
Example 3:
- Input:
nums = [2, 3, 4],minK = 1,maxK = 5 - Output:
0 - Explanation:
There is no occurrence ofminK(1) in the array, so no subarray qualifies.
- Input:
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i], minK, maxK <= 10^9
Hints Before You Start
- Hint 1: Think about how to efficiently count subarrays by processing the array in one pass rather than checking every possible subarray.
- Hint 2: Consider tracking the most recent positions where
minKandmaxKoccurred as well as the last index where an invalid element (outside the range[minK, maxK]) was encountered.
Approaches
Brute Force Approach
Idea:
- Enumerate every possible subarray of
numsand check if it meets the conditions (i.e., contains at least oneminK, onemaxK, and no elements outside the range[minK, maxK]).
Steps:
- Iterate over all possible starting indices.
- For each starting index, extend the subarray and check:
- Whether both
minKandmaxKare present. - Whether every element lies within the valid range.
- Whether both
- Count the subarrays that satisfy these conditions.
Complexity Analysis:
- Time Complexity: O(n²) or worse, since there are O(n²) subarrays to check and each check might be O(n) in the worst case.
- Space Complexity: O(1) (ignoring the space needed to store the input).
Drawbacks:
- The brute force solution is not practical for large inputs (n up to 10^5).
Optimal Approach (Using a Single Pass with Pointers)
Idea:
- Process the array in one pass while maintaining:
lastInvalid: The last index where an element was outside the range[minK, maxK]. Any subarray that crosses this index is invalid.lastMin: The most recent index wherenums[i]was equal tominK.lastMax: The most recent index wherenums[i]was equal tomaxK.
- For each index
i, if bothlastMinandlastMaxare valid (i.e. greater thanlastInvalid), then the number of valid subarrays ending atiis determined by the earliest occurrence betweenlastMinandlastMaxrelative tolastInvalid.
Detailed Steps:
-
Initialize:
lastInvalid = -1lastMin = -1lastMax = -1result = 0
-
Iterate over the array (index
i):- Step A: If
nums[i]is less thanminKor greater thanmaxK, updatelastInvalid = ibecause the current element invalidates any subarray containing it. - Step B: If
nums[i] == minK, updatelastMin = i. - Step C: If
nums[i] == maxK, updatelastMax = i. - Step D: The current index can form valid subarrays if both
lastMinandlastMaxare greater thanlastInvalid.
Calculatecount = max(0, min(lastMin, lastMax) - lastInvalid).
This number represents how many starting positions (after the last invalid index) can form a valid subarray ending ati. - Step E: Add
counttoresult.
- Step A: If
-
Return:
- The total count
result.
- The total count
Visual Example:
For nums = [1, 3, 5, 2, 7, 5], minK = 1, maxK = 5:
-
Initialization:
lastInvalid = -1,lastMin = -1,lastMax = -1,result = 0 -
i = 0 (value 1):
nums[0]equalsminK, solastMin = 0.- No update for
lastMax. min(lastMin, lastMax)is undefined (becauselastMax == -1), so no valid subarray ending at index 0.
-
i = 1 (value 3):
3is within[1, 5]but not equal to either bound.- No update for
lastMinorlastMax. - Still no valid subarray since
lastMaxis -1.
-
i = 2 (value 5):
nums[2]equalsmaxK, solastMax = 2.- Now, both
lastMin (0)andlastMax (2)are valid, and both >lastInvalid (-1). - Valid subarrays ending at index 2: count =
min(0, 2) - (-1)=0 - (-1)=1
→ The valid subarray is[1, 3, 5]. resultbecomes1.
-
i = 3 (value 2):
2is valid (in range).- No updates to
lastMinorlastMax. - Count =
min(lastMin, lastMax) - lastInvalid=min(0, 2) - (-1)=0 - (-1)=1
→ The valid subarray ending at index 3 is still determined by the position of1(sincemin(lastMin, lastMax)remains0), forming[1, 3, 5, 2]. resultbecomes2.
-
i = 4 (value 7):
7is outside the range[1, 5], updatelastInvalid = 4.- This resets the potential for valid subarrays until a new
minKormaxKis seen after index 4.
-
i = 5 (value 5):
nums[5]equalsmaxK, solastMax = 5.lastMinremains at0but note that index 0 is beforelastInvalid.- Since
lastMin (0)≤lastInvalid (4), no valid subarray ending at index 5 can be formed. resultremains2.
Complexity Analysis:
- Time Complexity: O(n), as we process each element exactly once.
- Space Complexity: O(1), only using a few variables for tracking indices.
Code Implementations
Python Code (Optimal Approach)
Java Code (Optimal Approach)
Common Mistakes
-
Not Resetting After an Invalid Element:
Failing to updatelastInvalidwhen encountering an element outside[minK, maxK]can lead to counting subarrays that include invalid elements. -
Incorrectly Handling Edge Cases:
Not checking whether bothminKandmaxKhave been seen (i.e.lastMinorlastMaxstill equals -1) before counting a subarray. -
Overcounting:
Miscalculating the number of valid starting positions for each ending index. Ensure you use the minimum of the last seen positions ofminKandmaxKand subtract the last invalid index.
Edge Cases
-
All Elements are Invalid:
For example, if every element innumsis outside[minK, maxK], then no subarray qualifies. -
Single Element Array:
Check if the single element equals bothminKandmaxK(whenminK == maxK) or is invalid. -
minK Equals maxK:
When both bounds are the same, every valid subarray must consist solely of that number. The algorithm still works with careful tracking.
Alternative Variations and Related Problems
Variations:
-
Subarrays with Exactly K Distinct Numbers:
Count the number of subarrays that contain exactly K distinct numbers. -
Subarrays with Bounded Maximum:
Count subarrays where the maximum element is less than or equal to a given value.
Related Problems for Further Practice:
GET YOUR FREE
Coding Questions Catalog
$197

$78
$78