![]() |
VOOZH | about |
Given a string S and an integer k, the task is to return the number of substrings in S of length k with no repeated characters.
Example:
Input: S = "geeksforgeeks", k = 5
Output: 4
Explanation: There are 4 substrings, they are: 'eksfo', 'ksfor', 'sforg', 'forge'.Input: S = "home", k = 5
Output: 0
Explanation: Notice k can be larger than the length of S. In this case, it is not possible to find any substring.
Approach:
We iterate over the input, expanding and contracting our window.
- Whenever the window has a repeating character, contract the window until there are no repeating characters.
- If length of window equals K, add 1 to count of good windows and then contract the window.
- This works because since we checked and got rid of repeating characters in step 1, our window of length K must NOT have any repeating characters.
- We contract our window in this step because we don't want a window that has a length GREATER than K.
Below points we also have to keep in mind:
- Keep track of our window bounds with left and right.
- Use a frequency dictionary to keep track of how many times we've seen a character.
- Remember to access frequency dictionary freq[S[right]] and not just freq[right]
- Check if right - left + 1 == K because we've added right to our frequency dictionary but we haven't actually incremented right yet
Steps-by-step approach:
Below is the implementation of the above approach:
Number of substrings of length 5 with no repeating characters: 4
Time Complexity: O(n), where n is the length of the string and k is window size
Auxiliary Space: O(min(n, K))