Find K-Length Substrings With No Repeated Characters - Problem

Given a string s and an integer k, return the number of substrings in s of length k with no repeated characters.

A substring is a contiguous sequence of characters within a string.

Example:

  • If s = "havefunonleetcode" and k = 5, the substring "havef" has repeated character 'e', but "onlee" has repeated 'e', while "funon" has no repeated characters.

Input & Output

Example 1 — Basic Case
$ Input: s = "havefunonleetcode", k = 5
Output: 6
💡 Note: The valid substrings are: "havef" (no duplicates), "avefe" (no duplicates), "vefun" (no duplicates), "efuno" (no duplicates), "funon" (no duplicates), "unon" has duplicate 'n', "nonl" has duplicate 'n', continuing this way we find 6 valid substrings.
Example 2 — Shorter String
$ Input: s = "home", k = 3
Output: 2
💡 Note: The substrings are: "hom" (all unique), "ome" (all unique). Both have no repeated characters, so answer is 2.
Example 3 — All Same Characters
$ Input: s = "aaa", k = 2
Output: 0
💡 Note: All possible substrings of length 2 are "aa" which has repeated character 'a', so no valid substrings exist.

Constraints

  • 1 ≤ s.length ≤ 104
  • 1 ≤ k ≤ 26
  • s consists of lowercase English letters only

Visualization

Tap to expand
Find K-Length Substrings: "home", k=3homeInput string: "home", k=3"hom" - All unique ✓"ome" - All unique ✓Check each k-length window for duplicate charactersOutput: 2 valid substrings
Understanding the Visualization
1
Input
String s and integer k
2
Process
Check each k-length substring for unique characters
3
Output
Count of valid substrings
Key Takeaway
🎯 Key Insight: Use sliding window with hash map to efficiently track character frequencies in O(n) time
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
856 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