Find K-Length Substrings With No Repeated Characters Problem
Description
LeetCode Problem 1100.
Given a string s and an integer k, return the number of substrings in s of length k with no repeated characters.
Example 1:
Input: s = "havefunonleetcode", k = 5
Output: 6
Explanation: There are 6 substrings they are: 'havef','avefu','vefun','efuno','etcod','tcode'.
Example 2:
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.
Constraints:
1 <= s.length <= 10^4sconsists of lowercase English letters.1 <= k <= 10^4
Solution
Approach: Sliding Window with Letter Counts
Checking each of the n - k + 1 substrings on its own costs O(n·k). But two neighboring windows share all but two characters: moving the window one step to the right adds s[i] and removes s[i - k]. So keep the letter counts of the current window and update them in O(1) per step.
Along with the counts, keep distinct, the number of letters whose count is above zero. It goes up when a count goes from 0 to 1 and down when a count drops back to 0. A window of length k has no repeated characters exactly when distinct == k: k characters with k different letters means each appears once.
Two edge cases:
- If
k > len(s), no window is ever complete, and the answer is0(Example 2). The loop handles this on its own, since the check only starts ati >= k - 1. - If
k > 26, some letter must repeat in every window (there are only 26 letters), so we can return0right away.
Complexity: O(n) time and O(1) extra space (26 counters).
class Solution:
def numKLenSubstrNoRepeats(self, s: str, k: int) -> int:
if k > 26: # some letter must repeat (also covers k > len(s) for long strings)
return 0
count = [0] * 26 # letter counts in the window s[i - k + 1 .. i]
distinct = 0
ans = 0
for i, ch in enumerate(s):
c = ord(ch) - ord("a")
if count[c] == 0:
distinct += 1
count[c] += 1
if i >= k: # drop the letter that left the window
old = ord(s[i - k]) - ord("a")
count[old] -= 1
if count[old] == 0:
distinct -= 1
if i >= k - 1 and distinct == k: # k letters, all different
ans += 1
return ans