01. Substrings of Length K with K-1 Distinct Elements
โ GFG solution to find count of substrings of length k with exactly k-1 distinct characters using optimized sliding window technique. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given a string s consisting only of lowercase alphabets and an integer k. Find the count of all substrings of length k which have exactly k-1 distinct characters.
๐ Examples
Example 1
Input: s = "abcc", k = 2
Output: 1
Explanation: Possible substrings of length k = 2 are:
- ab: 2 distinct characters
- bc: 2 distinct characters
- cc: 1 distinct character โ
Only one substring has exactly k-1 = 1 distinct character.Example 2
Input: s = "aabab", k = 3
Output: 3
Explanation: Possible substrings of length k = 3 are:
- aab: 2 distinct characters โ
- aba: 2 distinct characters โ
- bab: 2 distinct characters โ
All substrings have exactly k-1 = 2 distinct characters.๐ Constraints
$1 \le \text{s.size()} \le 10^5$
$2 \le k \le 27$
โ
My Approach
The optimal approach uses Sliding Window with Frequency Array technique to efficiently count substrings:
Sliding Window + Frequency Tracking
Initialize Window:
Process first
k-1characters to build initial frequency count.Track distinct character count for the initial window.
Slide the Window:
Add one character to the right and remove one from the left.
Update frequency array and distinct count accordingly.
Check if current window has exactly
k-1distinct characters.
Count Valid Substrings:
For each valid window (with
k-1distinct characters), increment result.Continue sliding until the entire string is processed.
Frequency Management:
Use array of size 26 for lowercase letters (constant space).
Increment distinct count when frequency becomes 1 (new character).
Decrement distinct count when frequency becomes 0 (character removed).
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the string. We traverse the string once with constant time operations per character.
Expected Auxiliary Space Complexity: O(1), as we use a fixed-size frequency array of 26 elements regardless of input size.
๐งโ๐ป Code (C++)
๐งโ๐ป Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Let's make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated