I am trying to find max substring possible with k unique letters. Is there a way i can do it recursive by string partition? My idea is to partition a string by cutting the last characters and if i find the first substring that contains k unique letters i return it.
For example k = 2, string = "abccd"
abccd ->
abcc, bccd ->
abc,bcc,bcc,ccd -> return bcc
def unique_l(sub, k):
u=0
visited = set()
for ch in sub:
if ch not in visited:
visited.add(ch)
u += 1
if u < k:
return -1
elif u == k:
return 1
else:
return 0
def find_sub(string,k):
if unique_l(string,k) == 1:
return string
if unique_l(string,k) == -1:
return "Not Found"
find_sub(string[0:len(string)-1],k) # Left
find_sub(string[1:len(string)],k) # Right
I know that i can do it in O(n) time using iteration but is there a way to do it recursive?