Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Google
Count The Number Of Good Subarrays

Count how many subarrays satisfy a frequency-based condition on their elements.

Acceptance 0%
Problem Statement

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 O(n2)O(n^2) checking is too slow.
  • Values are integers and may repeat.
  • An efficient solution should be near-linear or use a logarithmic-factor data structure.
Examples
Sample cases returned by the problem API.

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.

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.