Count how many subarrays satisfy a frequency-based condition on their elements.
Problem
Given an integer array, count the number of good subarrays. A subarray is considered good when it satisfies the problem's target condition on the elements inside it, typically involving the number of equal pairs or repeated values.
Your task is to return the total number of good subarrays in the array.
Notes
- A subarray is a contiguous segment of the array.
- Efficient solutions usually rely on tracking frequencies while expanding and shrinking a window.
- The goal is to count all valid subarrays, not just find one.
Input Format
- An integer array
nums. - A non-negative integer threshold or target value that defines when a subarray is good.
The exact condition depends on the problem statement, but it is based on the contents of a contiguous subarray.
Output Format
- Return an integer representing the number of good subarrays.
Constraints
- The array length may be large enough that checking is too slow.
- Values are integers and may repeat.
- An efficient solution should be near-linear or use a logarithmic-factor data structure.
Example 1
Input
nums = [1,1,1,1,1], k = 3
Output
6
Explanation
All subarrays of length at least 3 are good. The valid subarrays are the 3 subarrays of length 3, the 2 subarrays of length 4, and the 1 subarray of length 5.
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.