Sherlock and the Valid String

  • + 0 comments

    here f1==1 is for edge case - where only single alphabet is in string while all other have same frequency

    def isValid(s):
        lst=list(s)
        set_s=set(s)
        dct={}
        for i in set_s:
            dct[i]=lst.count(i)
        freqs=list(dct.values())
        unique=set(freqs)
        if len(unique)==1:
            return 'YES'
        elif len(unique)==2:
            f1,f2=sorted(unique)
            count_f1=freqs.count(f1)
            count_f2=freqs.count(f2)
            if count_f1==1 and (abs(f2-f1)==1 or f1==1):
                return 'YES'
            elif count_f2==1 and abs(f2-f1)==1:
                return 'YES'     
        return 'NO'