Problem statement

https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/

Solution

The idea is to use sliding window of length K, where we calculate counter of elements inside.

Complexity

It is O(n) for time and O(K) for space.

Code

class Solution:
    def numKLenSubstrNoRepeats(self, S, K):
        cnt, ans, n = Counter(), 0, len(S)
        for i, c in enumerate(S):
            cnt[c] += 1
            if i >= K:
                old = S[i - K]
                if cnt[old] == 1: cnt.pop(old)
                if cnt[old] >  1: cnt[old] -= 1
            if len(cnt) == K:
                ans += 1
        return ans