Count Subarrays With Fixed Bounds (LeetCode 2444): Solution and Explanation

Hard
Array
Queue
Sliding Window
Monotonic Queue

Count the subarrays whose minimum is exactly minK and whose maximum is exactly maxK.

Intuition

Any value below minK or above maxK ruins every subarray that contains it. Those positions act as walls that split the array into independent stretches.

Fix the right end i. A left end j works when the stretch j..i contains no wall, contains at least one minK and contains at least one maxK.

Moving j to the left only adds elements, so once j is at or before the latest minK and the latest maxK, both bounds are present. Moving it past the last wall breaks the subarray. The valid left ends are therefore one contiguous block: from bad + 1 up to min(lastMin, lastMax).

That block has max(0, min(lastMin, lastMax) - bad) positions, and the three indices are easy to keep up to date in one left-to-right pass.

Approach: One pass with three last-seen positions

  1. Set bad, lastMin and lastMax to -1 and total to 0 (64-bit).
  2. For each index i, if nums[i] is outside [minK, maxK] set bad = i.
  3. If nums[i] == minK set lastMin = i; if nums[i] == maxK set lastMax = i. Both can happen when minK equals maxK.
  4. Add max(0, min(lastMin, lastMax) - bad) to total.
  5. Return total.

Step-by-step example

nums = [1,3,5,2,7,5], minK = 1, maxK = 5
  1. i = 0, value 1: lastMin = 0. lastMax is still -1, so min(0, -1) - (-1) = 0. total = 0.
  2. i = 1, value 3: nothing changes. Still no 5 seen, total = 0.
  3. i = 2, value 5: lastMax = 2. min(0, 2) - (-1) = 1, so [1,3,5] counts. total = 1.
  4. i = 3, value 2: min(0, 2) - (-1) = 1, so [1,3,5,2] counts. total = 2.
  5. i = 4, value 7: outside the range, bad = 4. min(0, 2) - 4 is negative, add 0.
  6. i = 5, value 5: lastMax = 5, but lastMin = 0 is behind the wall, so min(0, 5) - 4 < 0. Add 0. The answer is 2.

Code: Python, Java, C++

1class Solution:
2    def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
3        total = 0
4        bad = last_min = last_max = -1
5        for i, x in enumerate(nums):
6            if x < minK or x > maxK:
7                bad = i
8            if x == minK:
9                last_min = i
10            if x == maxK:
11                last_max = i
12            total += max(0, min(last_min, last_max) - bad)
13        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is visited once and does a constant amount of work.

Space

O(1)

Only three indices and the running total are kept.

Other approaches

Split on walls, then count with two pointers (time O(n), space O(1))

Cut the array at every out-of-range value. Inside each piece, count subarrays that contain at least one minK and one maxK by subtracting the subarrays missing minK and missing maxK (inclusion-exclusion over runs). Same O(n) bound, more bookkeeping.

Check every subarray (time O(n^2), space O(1))

For each left end extend to the right while tracking the running min and max, counting when they equal minK and maxK and stopping at a wall. Simple, but O(n^2) in the worst case and too slow for n = 10^5.

Common mistakes

  • Using a 32-bit total. With n = 10^5 and minK = maxK the answer is about 5 * 10^9.
  • Using if / else if for the minK and maxK checks. When minK equals maxK one value must update both positions.
  • Forgetting the max(0, ...). When a bound was last seen before the wall, the difference is negative and must add nothing.
  • Resetting lastMin and lastMax at a wall is not needed and is easy to get wrong; comparing them with bad already ignores anything behind the wall.

Frequently asked questions

Why does min(lastMin, lastMax) give the rightmost valid left end?

The subarray must reach back far enough to include some minK and some maxK. The closest ones to i are at lastMin and lastMax, so the left end has to be at or before the smaller of the two. Any left end further left still includes both.

What happens when minK is greater than maxK?

Every value is either below minK or above maxK, so every index becomes a wall and the answer is 0. The same code handles it without a special case.

Is this really a sliding window problem?

It is a window whose left boundary is the last wall and whose valid starts end at min(lastMin, lastMax). Instead of moving a left pointer step by step, the window jumps whenever a wall appears.