Sherlock and the Valid String

  • + 0 comments
    from collections import Counter
    
    def isValid(s):
        sv = sorted(Counter(s).values())  # Count character frequencies and sort them
        
        # If all frequencies are the same, it's valid
        if len(set(sv)) == 1:
            return "YES"
        
        # Check cases where one frequency can be removed or adjusted to match the others
        if sv[0] == 1 and sv[1] == sv[-1]:
            return "YES"
        
        # Check if we can make it valid by reducing the highest frequency by one
        if sv[-1] - sv[-2] == 1 and sv[0] == sv[-2]:
            return "YES"
        
        return "NO"