Sherlock and the Valid String

  • + 0 comments

    My answer with Typescript, can be increase [point] to increase number of character can be remove

    function isValid(s: string): string {
        // 0. count every char in [s]
        let hash = new Map<string, number>()
        for (let c of s) hash.set(c, (hash.get(c) || 0) + 1)
    
        // 1. define a [value_average] and [point] that can be decreate
        let values = Array.from(hash.values())
        let value_average = values[0]
        let point = 1
    
        // 2. loop from 1 to end, check value gap and decreate point
        //  -> if [point] is out, return 'NO'
        //  -> orelse return 'YES'
        for (let i = 1; i < values.length; i++) {
            let value = values[i]
    
            if (value != value_average) {
                if (point == 0) return 'NO'
                point--
            }
        }
    
        return 'YES'
    }