Sherlock and the Valid String

  • + 0 comments
    def isValid(s):
        if len(s) <= 1:
            return "YES"
            
        freq = {}
        
        for i in s:
            freq[i] = freq.get(i, 0) + 1
        
        a = freq[s[0]]
        count_a = 0
        b = 0
        count_b = 0
        for i in freq:
            if freq[i] == a:
                count_a += 1
            elif not b:
                b = freq[i]
                count_b +=1
            elif freq[i] == b:
                count_b += 1
            else:
                return "NO"
        
        if count_a == 1:
            if a - b == 1 or a == 1:
                return "YES"
        elif count_b == 1:
            if b - a == 1 or b == 1:
                return "YES"
        elif count_a == 0 or count_b == 0:
            return "YES"
        
        return "NO"