Problem Description
Given an integer array and two integers minK and maxK, count the number of contiguous subarrays (fixed-bound subarrays) where the minimum value equals minK and the maximum value equals maxK.
Key Insights
- Use a sliding window to consider only valid segments where every element is between minK and maxK.
- Keep track of the most recent indices where minK and maxK appeared.
- Reset the window when an invalid element (less than minK or greater than maxK) is encountered.
- The number of valid subarrays ending at a position can be determined by the distance from the most recent invalid index to the minimum of the last occurrences of minK and maxK.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array since we make a single pass. Space Complexity: O(1), as we use only a constant amount of extra space.
Solution
Use a single traversal of the array while maintaining three pointers:
- lastInvalid: index of the most recent element that is outside the [minK, maxK] range.
- lastMin: index of the most recent occurrence of minK.
- lastMax: index of the most recent occurrence of maxK.
For each element:
- If it is invalid (not in [minK, maxK]), update lastInvalid.
- Update lastMin or lastMax if the element is equal to minK or maxK.
- The number of valid subarrays ending at the current index is max(0, min(lastMin, lastMax) - lastInvalid).
Accumulate this count over the array.