Find K-Length Substrings With No Repeated Characters — LeetCode 1100 Python Solution

MediumLeetCode PremiumHash TableStringSliding Window
Problem
#1100
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(\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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview