Find K-Length Substrings With No Repeated Characters - Problem
Given a string s and an integer k, you need to find how many substrings of length k exist that contain all unique characters (no repeated characters).
A substring is a contiguous sequence of characters within a string. For example, in the string "abc", the substrings of length 2 are "ab" and "bc".
Your task: Count all substrings of exactly length k where every character appears at most once.
Example: If s = "havefunonleetcode" and k = 5, then substrings like "havef" (has repeated characters) don't count, but "vefun" would count if all characters are unique.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "havefunonleetcode", k = 5
โบ
Output:
6
๐ก Note:
The 6 substrings of length 5 with no repeated characters are: "havef", "avefu", "vefun", "efuno", "funon", "nonle". Note that "onlee" has repeated 'e' so it doesn't count.
example_2.py โ No Valid Substrings
$
Input:
s = "home", k = 5
โบ
Output:
0
๐ก Note:
Since k=5 is greater than the length of string "home" (which is 4), there are no substrings of length 5, so the answer is 0.
example_3.py โ All Characters Repeated
$
Input:
s = "aaaa", k = 2
โบ
Output:
0
๐ก Note:
All possible substrings of length 2 are "aa", "aa", "aa". Each contains repeated character 'a', so none are valid.
Constraints
- 1 โค s.length โค 104
- 1 โค k โค s.length
- s consists of lowercase English letters only
- The string may contain repeated characters
Visualization
Tap to expand
Understanding the Visualization
1
Position the magnifying glass
Start with the magnifying glass over the first k letters
2
Count unique letters
Use a counter to track each letter type under the glass
3
Check if valid
If counter shows k different letters, all are unique - increment result
4
Slide the glass
Move glass one position right: remove leftmost letter from counter, add new rightmost letter
5
Repeat until end
Continue sliding and checking until glass reaches the end
Key Takeaway
๐ฏ Key Insight: The sliding window approach transforms an O(nรk) problem into O(n) by reusing character frequency information as we slide the window, rather than recounting characters for each new position.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code