MediumNo. 1100LeetCode Premium
Find K-Length Substrings With No Repeated Characters — LeetCode 1100 Python Solution
- Pattern
- Sliding Window
- Topics
- Hash Table, String, 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
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
- Time
- O(n)
- Space · auxiliary
- O(min(k, |Σ|)), where n is the length of the string s; and Σ is the character set, in this problem the character set is lowercase English letters, so |Σ| = 26
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
| No. | Problem | Difficulty |
|---|---|---|
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0030 | Substring with Concatenation of All Words | Hard |
| 0076 | Minimum Window Substring | Hard |
| 0187 | Repeated DNA Sequences | Medium |
| 0395 | Longest Substring with At Least K Repeating Characters | Medium |
| 0424 | Longest Repeating Character Replacement | Medium |
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, |Σ|)), 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.