Sherlock and the Valid String

  • + 0 comments

    I thought this one would be super easy but got humbled after I couldn't solve it in 15 minutes. Here is my Python solution!

    def isValid(s):
        s = Counter(s)
        frequencies = s.values()
        common = Counter(frequencies).most_common(1)[0][0]
        removed = False
        for frequency in frequencies:
            if abs(frequency - common) == 1 or (frequency != common and frequency == 1):
                if removed:
                    return "NO"
                else:
                    removed = True
            elif abs(frequency - common) > 1:
                return "NO"
        return "YES"