Count Subarrays With Fixed Bounds - Problem

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

A fixed-bound subarray of nums is a 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.

Return the number of fixed-bound subarrays.

A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
💡 Note: The fixed-bound subarrays are [1,3,5] and [1,3,5,2]. Both have min=1 and max=5.
Example 2 — Single Element
$ Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
💡 Note: All possible subarrays have min=max=1. There are 4+3+2+1=10 total subarrays.
Example 3 — No Valid Subarrays
$ Input: nums = [1,2,3], minK = 2, maxK = 4
Output: 0
💡 Note: No subarray can have max=4 since 4 is not in the array.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ minK, maxK ≤ 106
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Count Subarrays With Fixed Bounds135275min=1max=5max=5invalid[1,3,5][1,3,5,2]minK = 1, maxK = 5Result: 2 valid subarrays
Understanding the Visualization
1
Input
Array [1,3,5,2,7,5] with minK=1, maxK=5
2
Process
Find subarrays where min=1 and max=5
3
Output
Count = 2 valid subarrays
Key Takeaway
🎯 Key Insight: Track positions of boundary values and invalid elements to count valid subarrays efficiently
Asked in
Google 15 Amazon 12 Meta 8
22.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen