Minimum changes to a string to make all substrings distinct | javascript program to count number of changes to make all substrings distinct . ; Returns minimum changes to str so that no substring is repeated . ; If length is more than maximum allowed characters , we cannot get the required string . ; Variable to store count of distinct characters ; To store counts of different characters ; Answer is , n - number of distinct char ; Driver function
var MAX_CHAR = 26 ; function minChanges ( str ) { var n = str . length ; if ( n > MAX_CHAR ) return - 1 ; var dist_count = 0 ; var count = Array . from ( { length : MAX_CHAR } , ( _ , i ) => 0 ) ; for ( var i = 0 ; i < MAX_CHAR ; i ++ ) count [ i ] = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( count [ str . charAt ( i ) . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] == 0 ) dist_count ++ ; count [ str . charAt ( i ) . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } return ( n - dist_count ) ; } var str = " " ; document . write ( minChanges ( str ) ) ;