Count Subarrays With Fixed Bounds

Hard

Topics
ArrayQueueSliding WindowMonotonic Queue

A subarray is fixed-bound when its minimum is exactly a and its maximum is exactly b.

Given nums and the two bounds, return the number of fixed-bound subarrays.

The judge names the bounds a and b; LeetCode calls them minK and maxK.

Example 1

103152237455one that counts
equals the lower bound 1equals the upper bound 5outside the range, cannot be included
In [1,3,5,2,7,5] exactly 2 subarrays qualify, and the brace marks one of them. A subarray counts only when its smallest value is exactly 1 and its largest is exactly 5, so it has to contain both shaded kinds and must not reach across any dimmed cell, which lies outside the range entirely.
A subarray is contiguous, so one dimmed cell splits the array into independent stretches.
Input:  nums = [1,3,5,2,7,5], a = 1, b = 5
Output: 2
Explanation: The subarrays [1,3,5] and [1,3,5,2] qualify. Extending to the 7 pushes the maximum above 5.

Example 2

10111213one that counts
equals both bounds
A subarray counts only when its smallest value is exactly 1 and its largest is exactly 1, so it has to contain that value and must not reach across any dimmed cell, which lies outside the range entirely.
Input:  nums = [1,1,1,1], a = 1, b = 1
Output: 10
Explanation: Every one of the ten subarrays has both minimum and maximum equal to 1.

Example 3

103152237455one that counts
equals the lower bound 1equals the upper bound 7
Input:  nums = [1,3,5,2,7,5], a = 1, b = 7
Output: 2
Explanation: The window must now reach the 7, so it also has to include everything between it and the 1.

Constraints

  • 2 <= nums.length <= 10^5
  • 1 <= nums[i], a, b <= 10^6
Editorial — intuition, approach, complexity and pitfalls

Intuition

Three separate conditions have to hold at once, and seeing them as three is what makes this tractable. A qualifying subarray must contain at least one a, at least one b, and nothing outside the range — any value below a or above b is disqualifying because it would become the new minimum or maximum.

The third condition is the easiest to use: an out-of-range value is a hard wall. No qualifying subarray can straddle one, so the array splits into independent stretches and the answer is the sum over them.

Within a stretch, count the subarrays ending at each position. Such a subarray must start at or before the last a seen and at or before the last b seen — so the latest valid start is the earlier of those two, and the number of valid starts is that position minus the wall, counting from just after it.

Tracking three positions as the scan advances — the last a, the last b, and the last wall — answers the whole question in one pass with no window to shrink.

Approach

  1. Walk the array keeping three positions, all initialised to "before the start": the most recent index holding a, the most recent holding b, and the most recent out-of-range index.
  2. At each index, update whichever of the three applies. A value equal to both bounds updates both.
  3. The number of qualifying subarrays ending here is min(lastA, lastB) - lastWall, floored at zero: every start after the wall and at or before both bound sightings works.
  4. Add that to a running total.

Walkthrough

nums = [1, 3, 5, 2, 7, 5],  a = 1, b = 5

i  value  lastA  lastB  lastWall  min(A,B)-wall   add
0    1      0     -1      -1        -1 -> 0         0
1    3      0     -1      -1        -1 -> 0         0
2    5      0      2      -1         0 - -1 = 1     1
3    2      0      2      -1         0 - -1 = 1     1
4    7      0      2       4        out of range    0
5    5      0      5       4         0 - 4 < 0      0

total 2

The 7 at index 4 is a wall: after it, the only 1 in the array
is on the wrong side, so nothing further can qualify.

Complexity

  • Time — O(n): one pass with three positions and no inner loop.
  • Space — O(1): three indices and a total.

Common Pitfalls

  • Forgetting that a value can equal both bounds. When a == b the same index updates both positions, and example 2 depends on it.
  • Using if/elif for the two bound checks, which drops one of them in exactly that case.
  • Not flooring the count at zero. Before the first sighting of a bound, or just after a wall, the expression goes negative and silently subtracts from the total.
  • Trying to maintain a window and shrink it. The count-per-ending-index formulation needs no window, and a window has to handle the three conditions simultaneously, which is much fiddlier.

Full Solution — all languages

class Solution:
    def countSubarrays(self, nums, a, b):
        total = 0
        last_a = last_b = last_wall = -1
        for i, v in enumerate(nums):
            if v < a or v > b:
                last_wall = i
            if v == a:
                last_a = i
            if v == b:
                last_b = i
            total += max(0, min(last_a, last_b) - last_wall)
        return total
SensAI
Beta
Tap the mic to stop voice mode