Check if a string has all characters with same frequency with one variation allowed | Assuming only lower case characters ; To check a string S can be converted to a valid string by removing less than or equal to one character . ; freq [ ] : stores the frequency of each character of a string ; Find first character with non - zero frequency ; Find a character with frequency different from freq1 . ; If we find a third non - zero frequency or count of both frequencies become more than 1 , then return false ; } else If we find a third non - zero freq ; If counts of both frequencies is more than 1 ; Return true if we reach here ; Driver code
let CHARS = 26 ; function isValidString ( str ) { let freq = new Array ( CHARS ) ; for ( let i = 0 ; i < CHARS ; i ++ ) { freq [ i ] = 0 ; } for ( let i = 0 ; i < str . length ; i ++ ) { freq [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } let i , freq1 = 0 , count_freq1 = 0 ; for ( i = 0 ; i < CHARS ; i ++ ) { if ( freq [ i ] != 0 ) { freq1 = freq [ i ] ; count_freq1 = 1 ; break ; } } let j , freq2 = 0 , count_freq2 = 0 ; for ( j = i + 1 ; j < CHARS ; j ++ ) { if ( freq [ j ] != 0 ) { if ( freq [ j ] == freq1 ) { count_freq1 ++ ; } else { count_freq2 = 1 ; freq2 = freq [ j ] ; break ; } } } for ( let k = j + 1 ; k < CHARS ; k ++ ) { if ( freq [ k ] != 0 ) { if ( freq [ k ] == freq1 ) { count_freq1 ++ ; } if ( freq [ k ] == freq2 ) { count_freq2 ++ ; { return false ; } } if ( count_freq1 > 1 && count_freq2 > 1 ) { return false ; } } return true ; } let str = " " ; if ( isValidString ( str ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }