Rearrange string such that no pair of adjacent characters are of the same type | Function to rearrange given alphanumeric 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 ; Driver Code ; Given String ; Function call
def rearrange ( s ) : NEW_LINE INDENT s1 = [ ] NEW_LINE s2 = [ ] NEW_LINE for x in s : NEW_LINE INDENT if x . isalpha ( ) : NEW_LINE INDENT s1 . append ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT s2 . append ( x ) NEW_LINE DEDENT DEDENT n = len ( s1 ) NEW_LINE m = len ( s2 ) NEW_LINE if ( abs ( n - m ) > 1 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE flag = 0 NEW_LINE if ( n >= m ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT while ( i < n and j < m ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT s [ k ] = s1 [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT s [ k ] = s2 [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT flag = not flag NEW_LINE DEDENT return " " . join ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeks2020" NEW_LINE str1 = [ i for i in str ] NEW_LINE print ( rearrange ( str1 ) ) NEW_LINE DEDENT