Count Subarrays With Fixed Bounds

Count subarrays whose min equals minK and max equals maxK using a sliding-window with three trackers.

Hard
Time O(n) Space O(1)
LeetCode
4 min read
two-pointers sliding-window array

Problem#

Count fixed-bound subarrays of nums: those where the minimum is exactly minK and the maximum is exactly maxK.

Examples#

  • nums = [1,3,5,2,7,5], minK = 1, maxK = 52
  • nums = [1,1,1,1], minK = 1, maxK = 110

Constraints#

  • 2 <= nums.length <= 10^5, values in [1, 10^6].

Hints#

Hint 1
Walk left to right tracking the last index of minK, the last index of maxK, and the last index of a value outside [minK, maxK] (a “wall”).

Approach#

For each right index i, the number of valid subarrays ending at i equals min(lastMin, lastMax) - lastBad, clamped to zero. A “bad” element forbids any subarray spanning it; the smaller of the two anchor indices determines the latest start that includes both extremes.

Solution#

Count Subarrays With Fixed Bounds
class Solution {
public:
long long countSubarrays(vector<int>& nums, int minK, int maxK) {
long long ans = 0;
int lastMin = -1, lastMax = -1, lastBad = -1;
for (int i = 0; i < (int)nums.size(); ++i) {
int v = nums[i];
if (v < minK || v > maxK) lastBad = i;
if (v == minK) lastMin = i;
if (v == maxK) lastMax = i;
int validStart = min(lastMin, lastMax);
if (validStart > lastBad) ans += validStart - lastBad;
}
return ans;
}
};

Editorial#

The key invariant: a subarray [l..i] is valid iff (a) it contains at least one minK and at least one maxK, and (b) it contains no value outside [minK, maxK]. Condition (b) forces l > lastBad. Condition (a) forces l <= min(lastMin, lastMax). The count of valid l is min(lastMin, lastMax) - lastBad when positive, else zero. Each element is touched once.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.