Find K-Length Substrings With No Repeated Characters — LeetCode 1100 Python Solution
MediumLeetCode PremiumHash TableStringSliding Window
- Problem
- #1100
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s and an integer k, return the number of substrings in s of length k with no repeated characters.
Example
- Input
- s = "havefunonleetcode", k = 5
- Output
- 6
- Explanation
- There are 6 substrings they are: 'havef','avefu','vefun','efuno','etcod','tcode'.
Python solution
Python
class Solution:
def numKLenSubstrNoRepeats(self, s: str, k: int) -> int:
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(\min(k, |\Sigma|)), where n is the length of the string s; and \Sigma is the character set, in this problem the character set is lowercase English letters, so |\Sigma| = 26 auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1100. Find K-Length Substrings With No Repeated Characters is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
LeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 30Substring with Concatenation of All WordsHardLeetCode 76Minimum Window SubstringHardLeetCode 187Repeated DNA SequencesMediumLeetCode 395Longest Substring with At Least K Repeating CharactersMediumLeetCode 424Longest Repeating Character ReplacementMedium
Frequently asked questions
- How hard is LeetCode 1100. Find K-Length Substrings With No Repeated Characters?
- LeetCode 1100. Find K-Length Substrings With No Repeated Characters is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1100. Find K-Length Substrings With No Repeated Characters?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1100. Find K-Length Substrings With No Repeated Characters?
- The Python solution on this page uses O(\min(k, |\Sigma|)), where n is the length of the string s; and \Sigma is the character set, in this problem the character set is lowercase English letters, so |\Sigma| = 26 auxiliary space.
- What topics does LeetCode 1100. Find K-Length Substrings With No Repeated Characters cover?
- LeetCode 1100. Find K-Length Substrings With No Repeated Characters is tagged Hash Table, String and Sliding Window on LeetCode.
- Is LeetCode 1100. Find K-Length Substrings With No Repeated Characters a premium problem?
- Yes. LeetCode 1100. Find K-Length Substrings With No Repeated Characters is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.