# Find K-Length Substrings With No Repeated Characters in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a string S, we have to find the number of substrings of length K where no characters are repeated. So if S = “heyfriendshowareyou” and K is 5, then output will be 15, as the strings are [heyfr, eyfri, yfrie, frien, riend, iends, endsh, ndsho, dshow, showa, howar, oware, warey, areyo, reyou]

To solve this, we will follow these steps −

• create one empty map m, and left := 0 and right := -1 and ans := 0
• while right < length of string – 1
• if right – left + 1 = k, then
• increase ans by 1
• decrease m[str[left]] by 1
• increase left by 1
• continue to next iteration
• if str[right + 1] is not in m, then
• set m[str[right + 1]] := 1
• increase right by 1
• else if m[str[right + 1]] is 0, then
• increase m[str[right + 1]] by 1
• increase right by 1
• else
• decrease m[str[left]] by 1
• left := left + 1
• if right – left + 1 = k, then increase ans by 1
• return ans

## Example

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def numKLenSubstrNoRepeats(self, S, K):
m = {}
left = 0
right = -1
ans = 0
while right<len(S)-1:
if right - left + 1 == K:
ans+=1
m[S[left]]-=1
left+=1
continue
if S[right+1] not in m :
m[S[right+1]]=1
right+=1
elif not m[S[right+1]]:
m[S[right+1]]+=1
right+=1
else:
m[S[left]]-=1
left+=1
if right - left + 1 == K:
ans+=1
return ans
ob1 = Solution()
print(ob1.numKLenSubstrNoRepeats("heyfriendshowareyou", 5))

## Input

"heyfriendshowareyou"
5

## Output

"AIIOC"