Check if frequency of all characters can become same by one removal | PHP 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
< ? php $ M = 26 ; function getIdx ( $ ch ) { return ( $ ch - ' a ' ) ; } function allSame ( & $ freq , $ N ) { for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { if ( $ freq [ $ i ] > 0 ) { $ same = $ freq [ $ i ] ; break ; } } for ( $ j = $ i + 1 ; $ j < $ N ; $ j ++ ) if ( $ freq [ $ j ] > 0 && $ freq [ $ j ] != $ same ) return false ; return true ; } function possibleSameCharFreqByOneRemoval ( $ str ) { global $ M ; $ l = strlen ( $ str ) ; $ freq = array_fill ( 0 , $ M , NULL ) ; for ( $ i = 0 ; $ i < $ l ; $ i ++ ) $ freq [ getIdx ( $ str [ $ i ] ) ] ++ ; if ( allSame ( $ freq , $ M ) ) return true ; for ( $ c = ' a ' ; $ c <= ' z ' ; $ c ++ ) { $ i = getIdx ( $ c ) ; if ( $ freq [ $ i ] > 0 ) { $ freq [ $ i ] -- ; if ( allSame ( $ freq , $ M ) ) return true ; $ freq [ $ i ] ++ ; } } return false ; } $ str = " xyyzz " ; if ( possibleSameCharFreqByOneRemoval ( $ str ) ) echo " Yes " ; else echo " No " ; ? >