Sherlock and the Valid String

  • + 0 comments

    Python 3.10+ solution:

    #!/bin/python3
    
    import os
    from collections import Counter
    from typing import Literal
    
    #
    # Complete the 'is_valid' function below.
    #
    # The function is expected to return a STRING.
    # The function accepts STRING s as parameter.
    #
    
    
    def is_valid(s: str) -> Literal["NO", "YES"]:
        """Given a string, determine if it is valid."""
        y = "YES"
        if len(s) == 1:  # optional
            return y
        match len(counts := {*(frequencies := Counter(s).values())}):
            case 1:
                return y
            case 2:
                meta_freq = Counter(frequencies)
                lo, hi = sorted(counts)
                if 1 == lo == meta_freq[lo]:
                    return y
                if 1 == hi - lo == meta_freq[hi]:
                    return y
        return "NO"
    
    
    if __name__ == "__main__":
        result = is_valid(input())
        with open(os.environ["OUTPUT_PATH"], "w") as fptr:
            fptr.write(f"{result}\n")