text: Rearrange characters in a string such that no two adjacent are same using hashing | C # 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: using System ; using System . Collections . Generic ; class GFG { static Boolean isPossible ( char [ ] str ) { Dictionary < char , int > freq = new Dictionary < char , int > ( ) ; int max_freq = 0 ; for ( int j = 0 ; j < ( str . Length ) ; j ++ ) { if ( freq . ContainsKey ( str [ j ] ) ) { var v = freq [ str [ j ] ] + 1 ; freq . Remove ( str [ j ] ) ; freq . Add ( str [ j ] , v ) ; if ( freq [ str [ j ] ] > max_freq ) max_freq = freq [ str [ j ] ] ; } else { freq . Add ( str [ j ] , 1 ) ; if ( freq [ str [ j ] ] > max_freq ) max_freq = freq [ 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 ( ) ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }