Rearrange string such that no pair of adjacent characters are of the same type | Function to rearrange given alphanumeric String such that no two adjacent characters are of the same type ; Stores alphabets and digits ; Store the alphabets and digits separately in the Strings ; Stores the count of alphabets and digits ; If respective counts differ by 1 ; Desired arrangement not possible ; Stores the indexes ; Check if first character should be alphabet or digit ; Place alphabets and digits alternatively ; If current character needs to be alphabet ; If current character needs to be a digit ; Flip flag for alternate arrangement ; Return resultant String ; Given String ; Function Call
function rearrange ( s ) { let s1 = " " , s2 = " " , ans = " " ; let s3 = s . split ( " " ) ; for ( let x = 0 ; x < s3 . length ; x ++ ) { if ( s3 [ x ] >= ' ' && s3 [ x ] <= ' ' ) s1 += s3 [ x ] ; else s2 += s3 [ x ] ; } let n = s1 . length ; let m = s2 . length ; if ( Math . abs ( n - m ) > 1 ) return " " ; let i = 0 , j = 0 , k = 0 ; let flag = ( n >= m ) ? 1 : 0 ; while ( i < n && j < m ) { if ( flag != 0 ) ans += s1 [ i ++ ] ; else ans += s2 [ j ++ ] ; if ( flag == 1 ) flag = 0 ; else flag = 1 ; } return ans ; } let str = " " ; document . write ( rearrange ( str ) + " " ) ;