Convert to a string that is repetition of a substring of k length | Returns true if str can be converted to a string with k repeated substrings after replacing k characters . ; Length of string must be a multiple of k ; Map to store strings of length k and their counts ; If string is already a repetition of k substrings , return true . ; If number of distinct substrings is not 2 , then not possible to replace a string . ; One of the two distinct must appear exactly once . Either the first entry appears once , or it appears n / k - 1 times to make other substring appear once . ; Driver code
function checkString ( str , k ) { let n = str . length ; if ( n % k != 0 ) return false ; let mp = new Map ( ) ; for ( let i = 0 ; i < n ; i += k ) { if ( mp . has ( str . substring ( i , i + k ) ) ) mp . set ( str . substring ( i , i + k ) , mp . get ( str . substring ( i , i + k ) ) + 1 ) ; else mp . set ( str . substring ( i , i + k ) , 1 ) ; } if ( mp . size == 1 ) return true ; if ( mp . size != 2 ) { return false ; } for ( let [ key , value ] of mp . entries ( ) ) { if ( value == ( Math . floor ( n / k ) - 1 ) value == 1 ) return true ; } return false ; } if ( checkString ( " " , 2 ) ) document . write ( " " ) ; else document . write ( " " ) ;