Sherlock and the Valid String

  • + 0 comments

    Best one:

    def isValid(s):
        cts=Counter(s) #Count occurences of string
        ct2=Counter(cts.values()) #Count unique occurences of string occurences
        #if only one item in ct2 then all occurences are equal, 
        #if two items then check if diff is 1 and second most has a count of 1
        #Special case: if the second occurences of occurences equals 1, 
        #it means the second 1 occurrence can be removed to make a valid string.
        kc=ct2.most_common()
        return 'YES' if len(kc)==1 or (len(kc)==2 and \
         (((kc[1][0]-kc[0][0])==1 or kc[1][0]==1) and kc[1][1]==1)) else 'NO'