Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Google
Count Subarrays With Fixed Bounds

Count the number of contiguous subarrays whose minimum equals a given lower bound and whose maximum equals a given upper bound.

Acceptance 0%
Problem Statement

Count Subarrays With Fixed Bounds

Given an integer array nums and two integers minK and maxK, count how many contiguous subarrays satisfy all of the following:

  • every element in the subarray lies within the inclusive range [minK, maxK]
  • the minimum element in the subarray is exactly minK
  • the maximum element in the subarray is exactly maxK

Return the total number of such subarrays.

A subarray is a contiguous non-empty segment of the array.

The key challenge is to count all valid subarrays efficiently without checking every possible subarray.

Input Format

  • nums: an integer array
  • minK: the required minimum value
  • maxK: the required maximum value

Output Format

  • Return a single integer: the number of subarrays whose minimum is minK and maximum is maxK while all values stay within [minK, maxK].

Constraints

  • Subarrays must be contiguous and non-empty.
  • Values outside [minK, maxK] invalidate any subarray that includes them.
  • Count all valid subarrays, including overlapping ones.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,3,5,2,7,5], minK = 1, maxK = 5

Output

2

Explanation

The valid subarrays are [1,3,5] and [1,3,5,2].

Example 2

Input

nums = [1,1,1,1], minK = 1, maxK = 1

Output

10

Explanation

Every non-empty subarray is valid. There are 4 + 3 + 2 + 1 = 10 subarrays.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.