
You are given a string s consisting of lowercase English alphabets and an integer k. Your task is to find the length of the longest substring of s that contains exactly k distinct characters.
If no such substring exists, you should return -1.
The first line of input contains the string s.
The second line of input contains the integer k.
Print a single integer representing the length of the longest substring with exactly k distinct characters.
If no such substring is found, print -1.
A naive solution of checking every possible substring (O(N^2)) would be too slow for the given constraints.
aabacbebebe
3
7
We are looking for the longest substring with exactly 3 distinct characters.
- Substrings like `"aabac"` have 3 distinct characters (`a, b, c`) and length 5.
- The substring `"cbebebe"` has exactly 3 distinct characters (`c, b, e`) and has a length of 7. This is the optimal answer.
aaaa
2
-1
The string only contains one distinct character ('a'). It is impossible to form a substring with 2 distinct characters. Therefore, no valid substring exists.
The expected time complexity is O(N).
1 <= |s| <= 10^5
1 <= k <= 26
Time limit: 1 sec