Problem
Given a strings and an integer k, return the number of substrings in s of length k with no repeated characters.
Examples
Constraints
- 1 <= s.length <= 10^4
- s consists of lowercase English letters.
- 1 <= k <= 10^4
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 1100 with 12 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 1100 # by problem number
lcpy gen -s find_k_length_substrings_with_no_repeated_characters # by problem name
s and an integer k, return the number of substrings in s of length k with no repeated characters.
Input: s = "havefunonleetcode", k = 5
Output: 6
Explanation: There are 6 substrings they are: 'havef','avefu','vefun','efuno','etcod','tcode'.
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.
from collections import Counter
class Solution:
# Time: O(n)
# Space: O(1) - at most 26 distinct letters
def num_k_len_substr_no_repeats(self, s: str, k: int) -> int:
if k > len(s):
return 0
cnt = Counter(s[:k])
ans = int(len(cnt) == k)
for i in range(k, len(s)):
cnt[s[i]] += 1
cnt[s[i - k]] -= 1
if cnt[s[i - k]] == 0:
cnt.pop(s[i - k])
ans += int(len(cnt) == k)
return ans
| Time | Space |
|---|---|
| O(n) | O(1) - at most 26 distinct letters |