def solution(s): max_len=0 f=0 l=0 s_x=set(s) for i in s_x: first_d=s.find(i) last_d=s.rfind(i) if(first_d==last_d): pass else: distans=last_d-first_d if(distans>max_len): f=first_d l=last_d max_len=distans if(l==(len(s)-1)): l=None else: l=l+1 return s[f:l] s="abcdaaaa" print(solution(s))