Problem Summary
In this problem, we are given:
A string
sAn integer
k
Our task is to count all substrings that contain exactly k distinct characters.
A substring is a continuous part of a string.
This is one of the most important Sliding Window problems in Data Structures and Algorithms and is commonly asked in coding interviews, competitive programming, and Java DSA interview preparation.
Example
Input
s = "aba", k = 2
Output
3
Valid Substrings
["ab", "ba", "aba"]
These substrings contain exactly 2 distinct characters.
Understanding the Main Idea
At first glance, counting substrings with exactly k distinct characters may look difficult.
Instead of solving it directly, we use a very smart and optimized technique.
Important Formula
Exactly(K) = AtMost(K) - AtMost(K - 1)
This is the key concept behind solving this Sliding Window algorithm efficiently.
Why Does This Formula Work?
Let us understand this in simple words.
AtMost(K)
This includes all substrings that contain:
1 distinct character
2 distinct characters
3 distinct characters
... up to
Kdistinct characters
AtMost(K - 1)
This includes all substrings that contain:
1 distinct character
2 distinct characters
... up to
K - 1distinct characters
When we subtract them:
AtMost(K) - AtMost(K - 1)
we only get the substrings that contain exactly K distinct characters.
This optimization is widely used in advanced Sliding Window interview questions.
Step 1: Solve the AtMost(K) Problem
To solve the main problem efficiently, we first create a function that counts substrings with at most K distinct characters.
We use:
Sliding Window technique
Two pointers (
leftandright)Frequency array to track character counts
This approach gives an optimized O(n) time complexity solution.
How Sliding Window Works
The Sliding Window algorithm follows these steps:
Expand the Window
Move the right pointer forward and include new characters.
Track Character Frequency
Use a frequency array of size 26 because the string contains lowercase English letters.
Count Distinct Characters
Whenever a new character appears for the first time, increase the distinct count.
Shrink the Window
If distinct characters become greater than k, move the left pointer forward until the condition becomes valid again.
Count Valid Substrings
At every step, add:
(right - left + 1)
because all substrings ending at right are valid.

Join the conversation! Your thoughts help the community grow.