Check if frequency of all characters can become same by one removal | Javascript program to get same frequency character string by removal of at most one char ; Utility method to get index of character ch in lower alphabet characters ; Returns true if all non - zero elements values are same ; Get first non - zero element ; Check equality of each element with variable same ; Returns true if we can make all character frequencies same ; Fill frequency array ; If all frequencies are same , then return true ; Try decreasing frequency of all character by one and then check all equality of all non - zero frequencies ; Check character only if it occurs in str ; Driver code
let M = 26 ; function getIdx ( ch ) { return ( ch - ' ' ) ; } function allSame ( freq , N ) { let same = 0 ; let i ; for ( i = 0 ; i < N ; i ++ ) { if ( freq [ i ] > 0 ) { same = freq [ i ] ; break ; } } for ( let j = i + 1 ; j < N ; j ++ ) if ( freq [ j ] > 0 && freq [ j ] != same ) return false ; return true ; } function possibleSameCharFreqByOneRemoval ( str ) { let l = str . length ; let freq = new Array ( M ) ; for ( let i = 0 ; i < M ; i ++ ) { freq [ i ] = 0 ; } for ( let i = 0 ; i < l ; i ++ ) freq [ getIdx ( str [ i ] ) ] ++ ; if ( allSame ( freq , M ) ) return true ; for ( let c = ' ' ; c <= ' ' ; c ++ ) { let i = getIdx ( c ) ; if ( freq [ i ] > 0 ) { freq [ i ] -- ; if ( allSame ( freq , M ) ) return true ; freq [ i ] ++ ; } } return false ; } let str = " " ; if ( possibleSameCharFreqByOneRemoval ( str ) ) document . write ( " " ) ; else document . write ( " " ) ;