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
Sliding Window VisualizationString: "havefunonleetcode" k = 5havefunonPosition 1: Magnifier over "havef"Character Counter:h: 1a: 1v: 1e: 1, f: 1โœ“ 5 unique chars = kPosition 2: Slide right to "avefu"Updated Counter:a: 1v: 1e: 1f: 1, u: 1โœ“ 5 unique chars = k๐ŸŽฏ Key Insight: Efficiently update counter by removing old char and adding new charTime: O(n), Space: O(k) - Optimal solution!
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.
Asked in
Meta 45 Amazon 38 Google 32 Microsoft 28 Apple 22
42.4K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen