# Rearrange string such that no pair of adjacent characters are of the same type

• Last Updated : 21 Jun, 2021

Given alphanumeric string str, the task is to rearrange the string such that no two adjacent characters are of the same type, i.e., no two adjacent characters can be alphabets or digits. If no such arrangement is possible, print -1.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: str = “geeks2020”
Output: g2e0e2k0s

Input: str = “IPL20”
Output: I2P0L

Naive Approach: The simplest approach is to generate all possible permutation of the given string and for every permutation, check if it satisfies the given conditions or not. If fount to be true for any permutation, print that permutation. If no such permutation exists, then print -1.

Time Complexity: O(2N)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to store all the alphabets and the digits separately and rearrange them by placing them alternatively in the resultant string.  If the count of the alphabets and the digits differ by more than 1, print -1 as no desired arrangement is possible.

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach` `#include ``using` `namespace` `std;` `// Function to rearrange given``// alphanumeric string such that``// no two adjacent characters``// are of the same type``string rearrange(string s)``{``    ``// Stores alphabets and digits``    ``string s1 = ``""``, s2 = ``""``;` `    ``// Store the alphabets and digits``    ``// separately in the strings``    ``for` `(``char` `x : s) {``        ``isalpha``(x) ? s1.push_back(x)``                   ``: s2.push_back(x);``    ``}` `    ``// Stores the count of``    ``// alphabets and digits``    ``int` `n = s1.size();``    ``int` `m = s2.size();` `    ``// If respective counts``    ``// differ by 1``    ``if` `(``abs``(n - m) > 1)` `        ``// Desired arrangement``        ``// not possible``        ``return` `"-1"``;` `    ``// Stores the indexes``    ``int` `i = 0, j = 0, k = 0;` `    ``// Check if first character``    ``// should be alphabet or digit``    ``int` `flag = (n >= m) ? 1 : 0;` `    ``// Place alphabets and digits``    ``// alternatively``    ``while` `(i < n and j < m) {` `        ``// If current character``        ``// needs to be alphabet``        ``if` `(flag)``            ``s[k++] = s1[i++];` `        ``// If current character``        ``// needs to be a digit``        ``else``            ``s[k++] = s2[j++];` `        ``// Flip flag for alternate``        ``// arrangement``        ``flag = !flag;``    ``}` `    ``// Return resultant string``    ``return` `s;``}` `// Driver Code``int` `main()``{``    ``// Given String``    ``string str = ``"geeks2020"``;` `    ``// Function Call``    ``cout << rearrange(str) << endl;` `    ``return` `0;``}`

## Java

 `// Java program to implement``// the above approach``class` `GFG{` `// Function to rearrange given``// alphanumeric String such that``// no two adjacent characters``// are of the same type``static` `String rearrange(String s)``{``  ``// Stores alphabets and digits``  ``String s1 = ``""``, s2 = ``""``, ans = ``""``;``  ``char` `[]s3 = s.toCharArray();` `  ``// Store the alphabets and digits``  ``// separately in the Strings``  ``for` `(``char` `x : s3)``  ``{``    ``if``(x >= ``'a'` `&& x <= ``'z'``)``      ``s1 += x ;``    ``else``      ``s2 += x;``  ``}` `  ``// Stores the count of``  ``// alphabets and digits``  ``int` `n = s1.length();``  ``int` `m = s2.length();` `  ``// If respective counts``  ``// differ by 1``  ``if` `(Math.abs(n - m) > ``1``)` `    ``// Desired arrangement``    ``// not possible``    ``return` `"-1"``;` `  ``// Stores the indexes``  ``int` `i = ``0``, j = ``0``, k = ``0``;` `  ``// Check if first character``  ``// should be alphabet or digit``  ``int` `flag = (n >= m) ? ``1` `: ``0``;` `  ``// Place alphabets and digits``  ``// alternatively``  ``while` `(i < n && j < m)``  ``{``    ``// If current character``    ``// needs to be alphabet``    ``if` `(flag != ``0``)``      ``ans += s1.charAt(i++);` `    ``// If current character``    ``// needs to be a digit``    ``else``      ``ans += s2.charAt(j++);` `    ``// Flip flag for alternate``    ``// arrangement``    ``if``(flag == ``1``)``      ``flag = ``0``;``    ``else``      ``flag = ``1``;``  ``}` `  ``// Return resultant String``  ``return` `ans;``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``  ``// Given String``  ``String str = ``"geeks2020"``;` `  ``// Function Call``  ``System.out.print(rearrange(str) + ``"\n"``);``}``}` `// This code is contributed by gauravrajput1`

## Python3

 `# Python3 program to implement``# the above approach` `# Function to rearrange given``# alphanumeric such that no``# two adjacent characters``# are of the same type``def` `rearrange(s):``    ` `    ``# Stores alphabets and digits``    ``s1 ``=` `[]``    ``s2 ``=` `[]` `    ``# Store the alphabets and digits``    ``# separately in the strings``    ``for` `x ``in` `s:``        ``if` `x.isalpha():``            ``s1.append(x)``        ``else``:``            ``s2.append(x)` `    ``# Stores the count of``    ``# alphabets and digits``    ``n ``=` `len``(s1)``    ``m ``=` `len``(s2)` `    ``# If respective counts``    ``# differ by 1``    ``if` `(``abs``(n ``-` `m) > ``1``):` `        ``# Desired arrangement``        ``# not possible``        ``return` `"-1"` `    ``# Stores the indexes``    ``i ``=` `0``    ``j ``=` `0``    ``k ``=` `0` `    ``# Check if first character``    ``# should be alphabet or digit``    ``flag ``=` `0``    ``if` `(n >``=` `m):``        ``flag ``=` `1``    ``else``:``        ``flag ``=` `0` `    ``# Place alphabets and digits``    ``# alternatively``    ``while` `(i < n ``and` `j < m):` `        ``# If current character``        ``# needs to be alphabet``        ``if` `(flag):``            ``s[k] ``=` `s1[i]``            ``k ``+``=` `1``            ``i ``+``=` `1` `        ``# If current character``        ``# needs to be a digit``        ``else``:``            ``s[k] ``=` `s2[j]``            ``k ``+``=` `1``            ``j ``+``=` `1` `        ``# Flip flag for alternate``        ``# arrangement``        ``flag ``=` `not` `flag` `    ``# Return resultant string``    ``return` `"".join(s)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``# Given String``    ``str` `=` `"geeks2020"` `    ``str1 ``=` `[i ``for` `i ``in` `str``]` `    ``# Function call``    ``print``(rearrange(str1))` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program to implement``// the above approach``using` `System;``class` `GFG{` `// Function to rearrange given``// alphanumeric String such that``// no two adjacent characters``// are of the same type``static` `String rearrange(String s)``{``  ``// Stores alphabets and digits``  ``String s1 = ``""``, s2 = ``""``, ans = ``""``;``  ``char` `[]s3 = s.ToCharArray();` `  ``// Store the alphabets and digits``  ``// separately in the Strings``  ``foreach` `(``char` `x ``in` `s3)``  ``{``    ``if``(x >= ``'a'` `&& x <= ``'z'``)``      ``s1 += x ;``    ``else``      ``s2 += x;``  ``}` `  ``// Stores the count of``  ``// alphabets and digits``  ``int` `n = s1.Length;``  ``int` `m = s2.Length;` `  ``// If respective counts``  ``// differ by 1``  ``if` `(Math.Abs(n - m) > 1)` `    ``// Desired arrangement``    ``// not possible``    ``return` `"-1"``;` `  ``// Stores the indexes``  ``int` `i = 0, j = 0, k = 0;` `  ``// Check if first character``  ``// should be alphabet or digit``  ``int` `flag = (n >= m) ? 1 : 0;` `  ``// Place alphabets and digits``  ``// alternatively``  ``while` `(i < n && j < m)``  ``{``    ``// If current character``    ``// needs to be alphabet``    ``if` `(flag != 0)``      ``ans += s1[i++];` `    ``// If current character``    ``// needs to be a digit``    ``else``      ``ans += s2[j++];` `    ``// Flip flag for alternate``    ``// arrangement``    ``if``(flag == 1)``      ``flag = 0;``    ``else``      ``flag = 1;``  ``}` `  ``// Return resultant String``  ``return` `ans;``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``  ``// Given String``  ``String str = ``"geeks2020"``;` `  ``// Function Call``  ``Console.Write(rearrange(str) + ``"\n"``);``}``}` `// This code is contributed by 29AjayKumar`

## Javascript

 ``
Output:
`g2e0e2k00`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up