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: 5
💡 Note: The valid substrings of length 5 are: "havef" (h,a,v,e,f - all unique), "vefun" (v,e,f,u,n - all unique), "efuno" (e,f,u,n,o - all unique), "etcod" (e,t,c,o,d - all unique), and "tcode" (t,c,o,d,e - all unique). Total count is 5.
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
K-Length Substrings With No Repeated Characters INPUT String s: h a v e f u n o n l e e t c o d e s = "havefunonleetcode" k = 5 (length = 17) Window Size k=5: h a v e f Hash Map tracks char frequency {'h':1, 'a':1, 'v':1, 'e':1, 'f':1} All unique = Valid! count = 5 chars ALGORITHM STEPS 1 Initialize Hash Map Create empty map for char count 2 Build First Window Add first k chars to hash map 3 Check Valid Window If map.size == k, increment count 4 Slide Window Right Remove left char, add right char Valid Windows Found: [havef] - OK (5 unique) [avefu] - OK (5 unique) [vefun] - OK (5 unique) [efuno] - OK (5 unique) [funon] - X (n repeats) ... [tcode] - OK (5 unique) [ecode] - X (e repeats) FINAL RESULT Output: 6 6 valid substrings found All Valid Substrings: 1. "havef" 2. "avefu" 3. "vefun" 4. "efuno" 5. "tcod e" 6. "odetc" Key Insight: Use a Hash Map to track character frequencies in the sliding window. A window is valid when the map size equals k (all k characters are unique). Slide by removing left char and adding right char. Time: O(n), Space: O(k) where n = string length. TutorialsPoint - Find K-Length Substrings With No Repeated Characters | Hash Approach
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