Count Subarrays With Fixed Bounds

You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies both of these conditions: - The **minimum** value in the subarray is equal to `minK`. - The **maximum** value in the subarray is equal to `maxK`. Return *the **number** of fixed-bound subarrays*. A **subarray** is a **contiguous** part of an array.

30:00

Count Subarrays With Fixed Bounds
hard
Free written solution
Topics
Companies

You are given an integer array nums and two integers minK and maxK.

A fixed-bound subarray of nums is a subarray that satisfies both of these conditions:

  • The minimum value in the subarray is equal to minK.
  • The maximum value in the subarray is equal to maxK.

Return the number of fixed-bound subarrays.

A subarray is a contiguous part of an array.

Example 1:
Input: {"nums":[1,3,5,2,7,5],"minK":1,"maxK":5}
Output: 2
Constraints:
  • 2≤nums.length≤1052 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i],minK,maxK≤1061 \leq \text{nums}[i], \text{minK}, \text{maxK} \leq 10^6

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,3,5,2,7,5],"minK":1,"maxK":5}

A subarray ending at i is valid when it holds no value outside [1, 5], at least one 1 and at least one 5. Track three positions: the last bad value, the last 1 and the last 5.

= minK (1)

= maxK (5)

outside range (wall)

valid starts

nums

1
3
5
2
7
5

0

1

2

3

4

5

starts that work = min(-1, -1) - (-1) = 0

A start must be right of the wall and at or left of both the last minK and the last maxK.

added

+0

total

0

Variables
VariableValue
total0
bad-1
last_min-1
last_max-1
DepthFunction Call
Stack empty
0/13