Longest K unique characters substring
Problem Link: https://practice.geeksforgeeks.org/problems/longest-k-unique-characters-substring0853/1
class Solution:
def longestKSubstr(self, s, k):
# code here
c=0
j=0
ans=0
d={}
n=len(s)
for i in range(n):
if(s[i] not in d):
d[s[i]]=1
else:
d[s[i]]+=1
while(len(d)>k):
if(d[s[j]]>1):
d[s[j]]-=1
j+=1
else:
del d[s[j]]
j+=1
ans=max(ans,i-j+1)
### If k is larger than
### the size of dictionary
if(i-j+1==n and k>len(d)):
ans=-1
return ans
PreviousLongest Substring Without Repeating Characters (Leetcode 3)Next***Longest Repeating Character Replacement (Leetcode 424)
Last updated