The "Count Subarrays With Fixed Bounds interview question" is a difficult counting task. You are given an array and two integers, minK and maxK. A subarray is considered valid if its minimum element is exactly minK and its maximum element is exactly maxK, and all elements are within the range [minK, maxK]. You need to count the total number of such valid subarrays.
Tech giants like Adobe, Google, and Meta ask the "Count Subarrays With Fixed Bounds coding problem" because it requires tracking three different "last seen" indices simultaneously. It is a true test of linear-time logic and the ability to handle multiple constraints in a single pass. It evaluations "Sliding Window interview pattern" and "Two Pointers" skills at a high level.
This problem is solved using a Single Pass with Boundary Tracking.
badIdx where an element was outside the range [minK, maxK].minIdx where minK was seen and maxIdx where maxK was seen.i:
arr[i] is out of range, update badIdx = i.arr[i] == minK, update minIdx = i.arr[i] == maxK, update maxIdx = i.i is max(0, min(minIdx, maxIdx) - badIdx). This formula calculates how many starting points exist between the last "bad" element and the first occurrence of both required bounds.Array: [1, 3, 5, 2, 7, 5], minK=1, maxK=5
minIdx=0, badIdx=-1. (No max seen yet).maxIdx=2.
min(0, 2) - (-1) = 1. Subarray: [1, 3, 5].min(0, 2) - (-1) = 1. Subarray: [1, 3, 5, 2].badIdx=4. (Resetting).
Result: 2.Practice problems where you track the "last valid" or "last invalid" index. This "Two Pointers interview pattern" is a powerful way to solve complex subarray constraints in time with extra space.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sliding Window Maximum | Hard | Solve | |
| Max Value of Equation | Hard | Solve | |
| Constrained Subsequence Sum | Hard | Solve | |
| Continuous Subarrays | Medium | Solve | |
| Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit | Medium | Solve |