VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-number-of-substrings-with-exactly-k-distinct-characters/

⇱ Count substrings with k distinct characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count substrings with k distinct characters

Last Updated : 14 Aug, 2025

Given a string s consisting of only lowercase English letters and an integer k, count the total number of substrings (not necessarily distinct) of s that contain exactly k distinct characters.
Note:

  • A substring is a contiguous sequence of characters within a string.
  • Substrings that are identical but occur at different positions should each be counted separately.

Examples:

Input: s = "abc", k = 2
Output: 2
Explanation: Possible substrings are ["ab", "bc"]

Input: s = "aba", k = 2
Output: 3
Explanation: Possible substrings are ["ab", "ba", "aba"]

Input: s = "aa", k = 1
Output: 3
Explanation: Possible substrings are ["a", "a", "aa"]

[Naive Approach] Checking all Substrings - O(n^2) time and O(1) space

The idea is to check every possible substring by iterating through all possible starting positions (i) and ending positions (j) in the string. For each substring, maintain a boolean array to track distinct characters and a counter for the number of distinct characters. As it expands the substring from left to right, it updates the distinct character count by checking if each new character has been seen before. Whenever the number of distinct characters exactly matches the given k, it increments the answer count.


Output
2

[Efficient Approach] Using Sliding Window Method - O(n) time and O(1) space

The idea is to use sliding window technique to efficiently count substrings with at most k distinct characters, and then subtract the count of substrings with at most k-1 distinct characters to obtain the number of substrings with exactly k distinct characters.

Step by step Implementation:

  • Use a sliding window with an array of size 26 to track character frequencies.
  • Expand the window to the right, adding characters.
  • Shrink the window from the left when distinct characters exceed k.
  • Count all valid substrings within the window.
  • Subtract substrings with k-1 distinct characters from k distinct characters.

Output
2
Comment
Article Tags: