text: Rearrange characters in a string such that no two adjacent are same using hashing | Java implementation of the approach ; 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
code: import java . util . * ; class GFG { static boolean isPossible ( char [ ] str ) { Map < Character , Integer > freq = new HashMap < > ( ) ; int max_freq = 0 ; for ( int j = 0 ; j < ( str . length ) ; j ++ ) { if ( freq . containsKey ( str [ j ] ) ) { freq . put ( str [ j ] , freq . get ( str [ j ] ) + 1 ) ; if ( freq . get ( str [ j ] ) > max_freq ) max_freq = freq . get ( str [ j ] ) ; } else { freq . put ( 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 ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; if ( isPossible ( str . toCharArray ( ) ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }