Problem Overview
Given an array of positive integers arr[] and an integer k, your task is to:
Count the number of subarrays that contain at most
kdistinct integers.
A subarray is a contiguous part of the array.
Example
Input
arr = [1, 2, 2, 3]
k = 2
Output
9
Valid Subarrays
[1], [2], [2], [3],
[1,2], [2,2], [2,3],
[1,2,2], [2,2,3]
Key Idea: Sliding Window
A brute-force approach (checking all subarrays) takes O(n²) time, which is too slow.
Instead, we use:
Sliding Window
HashMap (Frequency Map)
Intuition
We maintain a window [left, right] such that:
It contains at most
kdistinct elements.Expand
rightto include new elements.If distinct elements exceed
k, moveleftforward to shrink the window.
Key Observation
At each step:
The number of valid subarrays ending at index right is:
(right - left + 1)
Because all these subarrays are valid:
[right], [right-1, right], ..., [left, right]
Step-by-Step Dry Run
Input
arr = [1, 2, 2, 3], k = 2
| Step | Window | Distinct | Count Added | Total |
|---|---|---|---|---|
| r=0 | [1] | 1 | 1 | 1 |
| r=1 | [1,2] | 2 | 2 | 3 |
| r=2 | [1,2,2] | 2 | 3 | 6 |
| r=3 | [2,2,3] | 2 | 3 | 9 |

Join the conversation! Your thoughts help the community grow.