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 Bounds INPUT nums array: 1 i=0 3 i=1 5 i=2 2 i=3 7 i=4 5 i=5 minK = 1 maxK = 5 Constraints: - Subarray must contain minK - Subarray must contain maxK - min(subarray) == minK - max(subarray) == maxK Valid subarrays to find: [1,3,5] and [1,3,5,2] (7 exceeds maxK=5) ALGORITHM STEPS 1 Track Positions lastMin: last index of minK lastMax: last index of maxK 2 Track Bad Index lastBad: index where nums[i] < minK or > maxK 3 Calculate Count For each i, valid start is from lastBad+1 to min(lastMin, lastMax) 4 Add to Result count += max(0, min(lastMin,lastMax) - lastBad) At i=2: lastMin=0, lastMax=2 lastBad=-1, count += 0-(-1)=1 At i=3: count += 0-(-1)=1 At i=4: 7>5, lastBad=4, skip FINAL RESULT Found 2 valid subarrays: Subarray 1: [1,3,5] min=1 (OK), max=5 (OK) Valid: indices 0-2 Subarray 2: [1,3,5,2] min=1 (OK), max=5 (OK) Valid: indices 0-3 OUTPUT 2 Total fixed-bound subarrays = 2 Time: O(n) | Space: O(1) Key Insight: For each position i, we track the last occurrence of minK and maxK, and the last "bad" index. The number of valid subarrays ending at i = max(0, min(lastMin, lastMax) - lastBad). TutorialsPoint - Count Subarrays With Fixed Bounds | Optimal O(n) Sliding Window Approach
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