Rearrange characters in a string such that no two adjacent are same using hashing | Function that returns true if it is possible to rearrange the characters of the string such that no two consecutive characters are same ; To store the frequency of each of the character ; To store the maximum frequency so far ; If possible ; Driver code
function isPossible ( str ) { let freq = new Map ( ) ; let max_freq = 0 ; for ( let j = 0 ; j < ( str . length ) ; j ++ ) { if ( freq . has ( str [ j ] ) ) { freq . set ( str [ j ] , freq . get ( str [ j ] ) + 1 ) ; if ( freq . get ( str [ j ] ) > max_freq ) max_freq = freq . get ( str [ j ] ) ; } else { freq . set ( str [ j ] , 1 ) ; if ( freq . get ( str [ j ] ) > max_freq ) max_freq = freq . get ( str [ j ] ) ; } } if ( max_freq <= ( str . length - max_freq + 1 ) ) return true ; return false ; } let str = " " ; if ( isPossible ( str . split ( ' ' ) ) ) document . write ( " " ) ; else document . write ( " " ) ;