1

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?

no1special
  • 49
  • 3

1 Answers1

1

You can use recursion with a generator:

from collections import Counter
def group(d, k):
  for i in range(len(d)):
    for b in range(i, len(d)):
       if len(set((_r:=d[i:b]))) == k:
          yield _r
       yield from group(_r, k)


r = max(group("abccd", 2), key=len)

Output:

'bcc'
Ajax1234
  • 58,711
  • 7
  • 46
  • 83
  • I'm not sure how this _r:=d[i:b] and yield statment works – no1special Dec 17 '19 at 21:01
  • 1
    @no1special `_r:=d[i:b]` is an [assignment expression](https://stackoverflow.com/questions/50297704/syntax-and-assignment-expressions-what-and-why). Essentially, it can create a new name in a scope without an explicit definition. `yield` is part of a generator, it enables value generation on the fly by accessing values pointed to in memory. – Ajax1234 Dec 17 '19 at 21:05