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.
Examples:
Input: str = “aabcd”
Output: bdaac
No two adjacent characters are neighbours in English alphabets.Input: str = “aab”
Output: -1
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:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function that returns true if the // current arrangement is valid bool check(string s) { for (int i = 0; i + 1 < s.size(); ++i) if (abs(s[i] - s[i + 1]) == 1) return false; return true; } // Function to rearrange the characters of // the string such that no two neighbours // in the English alphabets appear together void Rearrange(string str) { // To store the odd and the // even positioned characters string odd = "", even = ""; // Traverse through the array for (int i = 0; i < str.size(); ++i) { if (str[i] % 2 == 0) even += str[i]; else odd += str[i]; } // Sort both the strings sort(odd.begin(), odd.end()); sort(even.begin(), even.end()); // Check possibilities if (check(odd + even)) cout << odd + even; else if (check(even + odd)) cout << even + odd; else cout << -1; } // Driver code int main() { string str = "aabcd"; Rearrange(str); return 0; } |
Java
// Java implementation of the approach import java.util.*; class GFG { // Function that returns true if the // current arrangement is valid static boolean check(String s) { for (int i = 0; i + 1 < s.length(); ++i) { if (Math.abs(s.charAt(i) - s.charAt(i + 1)) == 1) { return false; } } return true; } // Function to rearrange the characters of // the string such that no two neighbours // in the English alphabets appear together static void Rearrange(String str) { // To store the odd and the // even positioned characters String odd = "", even = ""; // Traverse through the array for (int i = 0; i < str.length(); ++i) { if (str.charAt(i) % 2 == 0) { even += str.charAt(i); } else { odd += str.charAt(i); } } // Sort both the strings odd = sort(odd); even = sort(even); // Check possibilities if (check(odd + even)) { System.out.print(odd + even); } else if (check(even + odd)) { System.out.print(even + odd); } else { System.out.print(-1); } } // Method to sort a string alphabetically public static String sort(String inputString) { // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray); } // Driver code public static void main(String[] args) { String str = "aabcd"; Rearrange(str); } } // This code is contributed by 29AjayKumar |
Python3
# Python3 implementation of the approach # Function that returns true if the # current arrangement is valid def check(s): for i in range(len(s) - 1): if (abs(ord(s[i]) - ord(s[i + 1])) == 1): return False return True # Function to rearrange the characters # of the such that no two neighbours # in the English alphabets appear together def Rearrange(Str): # To store the odd and the # even positioned characters odd, even = "","" # Traverse through the array for i in range(len(Str)): if (ord(Str[i]) % 2 == 0): even += Str[i] else: odd += Str[i] # Sort both the Strings odd = sorted(odd) even = sorted(even) # Check possibilities if (check(odd + even)): print("".join(odd + even)) elif (check(even + odd)): print("".join(even + odd)) else: print(-1) # Driver code Str = "aabcd" Rearrange(Str) # This code is contributed # by Mohit Kumar |
C#
// C# implementation of the approach using System; class GFG { // Function that returns true if the // current arrangement is valid static Boolean check(String s) { for (int i = 0; i + 1 < s.Length; ++i) { if (Math.Abs(s[i] - s[i + 1]) == 1) { return false; } } return true; } // Function to rearrange the characters of // the string such that no two neighbours // in the English alphabets appear together static void Rearrange(String str) { // To store the odd and the // even positioned characters String odd = "", even = ""; // Traverse through the array for (int i = 0; i < str.Length; ++i) { if (str[i] % 2 == 0) { even += str[i]; } else { odd += str[i]; } } // Sort both the strings odd = sort(odd); even = sort(even); // Check possibilities if (check(odd + even)) { Console.Write(odd + even); } else if (check(even + odd)) { Console.Write(even + odd); } else { Console.Write(-1); } } // Method to sort a string alphabetically public static String sort(String inputString) { // convert input string to char array char []tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return new String(tempArray); } // Driver code public static void Main(String[] args) { String str = "aabcd"; Rearrange(str); } } // This code is contributed by 29AjayKumar |
bdaac
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.
Recommended Posts:
- 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
- Count of character pairs at same distance as in English alphabets
- For each lowercase English alphabet find the count of strings having these alphabets
- Rearrange string such that no pair of adjacent characters are of the same type
- Minimum string such that every adjacent character of given string is still adjacent
- Longest substring of vowels with no two adjacent alphabets same
- Rearrange array such that difference of adjacent elements is in descending order
- Count characters at same position as in English alphabet
- Sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged
- Remove consecutive alphabets which are in same case
- Minimum characters that are to be inserted such that no three consecutive characters are same
- Remove all characters other than alphabets from string
- String with k distinct characters and no same characters adjacent
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Minimum Cost of deletions such that string does not contains same consecutive characters
- Rearrange the given string such that all prime multiple indexes have same character
- Rearrange an array to minimize sum of product of consecutive pair elements
- 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
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.

