Sherlock and the Valid String

  • + 0 comments

    My Solution in python:

    def isValid(s):
        counter = Counter(s)
    
        # If all characters appear the same number of times, return "YES"
        if len(set(counter.values())) == 1:
            return "YES"
        
        counter_copy1 = counter.copy()
        max_key = max(counter_copy1, key=lambda x: counter_copy1[x])
        counter_copy1[max_key] -=1
    
        # If all characters appear the same number of times after removing one character, return "YES"
        if len(set(counter_copy1.values())) == 1:
            return "YES"
    
        counter_copy2 = counter.copy()
        min_key = min(counter_copy2, key=lambda x: counter_copy2[x])
        counter_copy2[min_key] -=1
        if counter_copy2[min_key] == 0:
            del counter_copy2[min_key]
    
        # If all characters appear the same number of times after removing one character, return "YES"
        if len(set(counter_copy2.values())) == 1:
            return "YES"
    
        # If none of the conditions are satisfied, return "NO"
        return "NO"