Given string str of size N consists of lower-case English alphabets. The task is to find the arrangement of the characters of the string such that no two adjacent characters are neighbors in English alphabets. In case of multiple answers print any of them. If no such arrangement is possible then print -1.
Input: str = “aabcd”
No two adjacent characters are neighbours in English alphabets.
Input: str = “aab”
Approach: Traverse through the string and store all odd positioned characters in a string odd and even positioned characters in another string even i.e. every two consecutive characters in both the strings will have an absolute difference in ASCII values of at least 2. Then sort both the strings. Now, if any of the concatenation (even + odd) or (odd + even) is valid then print the valid arrangement else it is not possible to rearrange the string in the required way.
Below is the implementation of the above approach:
- Rearrange characters in a string such that no two adjacent are same
- Rearrange characters in a string such that no two adjacent are same using hashing
- Permutation of a string with maximum number of characters greater than its adjacent characters
- String with k distinct characters and no same characters adjacent
- Remove all characters other than alphabets from string
- Rearrange a string so that all same characters become d distance away
- Rearrange a string so that all same characters become atleast d distance away
- Strings formed from given characters without any consecutive repeating characters
- Minimum characters that are to be inserted such that no three consecutive characters are same
- C program to swap adjacent characters of a String
- Group consecutive characters of same type in a string
- Reduce the string by removing K consecutive identical characters
- Minimum replacements to make adjacent characters unequal in a ternary string
- Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
- Count characters at same position as in English alphabet
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.