Count Subarrays With Fixed Bounds
Problem Statement
You are given an integer array nums and two numbers minK and maxK.
A contiguous subarray is a fixed-bound subarray if its smallest value is exactly minK and its largest value is exactly maxK.
Count the fixed-bound subarrays.
This is a LeetCode Hard. It sits at position 4 of the Exactly K sub-pattern because the usual atMost − atMost trick does not fit it directly.
An integer array nums and two integers minK and maxK.
The number of subarrays whose minimum is minK and whose maximum is maxK. The count can be large, so it is returned as a 64-bit number.
The fixed-bound subarrays are [1,3,5] and [1,3,5,2]. Anything that includes the 7 has max 7, and [5] alone has min 5, not 1.
Every subarray has min 1 and max 1. There are 4·5/2 = 10 subarrays.
- • 2 ≤ nums.length ≤ 10^5
- • 1 ≤ nums[i], minK, maxK ≤ 10^6
- • The answer can exceed the int range — use a 64-bit type.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Fix each start, grow the end, track min and max
For each right, good starts are lastBad+1 … min(lastMin, lastMax)
For every start, move the end right while keeping the running minimum and maximum. If an out-of-range value shows up, stop — every longer subarray contains it too. Count one whenever min = minK and max = maxK.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.