Related Articles

# Rearrange characters in a sorted string such that no pair of adjacent characters are the same

• Last Updated : 13 Aug, 2021

Given a sorted string S consisting of N lowercase characters, the task is to rearrange characters in the given string such that no two adjacent characters are the same. If it is not possible to rearrange as per the given criteria, then 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: S = “aaabc”
Output: abaca

Input: S = “aa”
Output: -1

Approach: The given problem can be solved by using the Two-Pointer Technique. Follow the steps below to solve this problem:

• Iterate over the characters of the string S and check if no two adjacent characters are the same in the string then print the string S.
• Otherwise, if the size of the string is 2 and has the same characters, then print “-1”.
• Initialize three variables, say, i as 0, j as 1, and k as 2 to traverse over the string S.
• Iterate while k is less than N and perform the following steps:
• If S[i] is not equal to S[j], then increment i and j by 1, and increment k by 1, if the value of j is equal to k.
• Else if S[j] equals S[k], increment k by 1.
• Else, swap s[j] and s[k] and increment i and j by 1, and if j is equal to k, then increment k by 1.
• After completing the above steps reverse the string S.
• Finally, iterate over the characters of the string S and check if no two adjacent characters are the same. If found to be true then print string S. Otherwise, print “-1”.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to check if a string S``// contains pair of adjacent``// characters that are equal or not``bool` `isAdjChar(string& s)``{``    ``// Traverse the string S``    ``for` `(``int` `i = 0; i < s.size() - 1; i++) {` `        ``// If S[i] and S[i+1] are equal``        ``if` `(s[i] == s[i + 1])``            ``return` `true``;``    ``}` `    ``// Otherwise, return false``    ``return` `false``;``}` `// Function to rearrange characters``// of a string such that no pair of``// adjacent characters are the same``void` `rearrangeStringUtil(string& S, ``int` `N)``{``    ``// Initialize 3 variables``    ``int` `i = 0, j = 1, k = 2;` `    ``// Iterate until k < N``    ``while` `(k < N) {` `        ``// If S[i] is not equal``        ``// to S[j]``        ``if` `(S[i] != S[j]) {` `            ``// Increment i and j by 1``            ``i++;``            ``j++;` `            ``// If j equals k and increment``            ``// the value of K by 1``            ``if` `(j == k) {``                ``k++;``            ``}``        ``}` `        ``// Else``        ``else` `{` `            ``// If S[j] equals S[k]``            ``if` `(S[j] == S[k]) {` `                ``// Increment k by 1``                ``k++;``            ``}` `            ``// Else``            ``else` `{` `                ``// Swap``                ``swap(S[k], S[j]);` `                ``// Increment i and j``                ``// by 1``                ``i++;``                ``j++;` `                ``// If j equals k``                ``if` `(j == k) {` `                    ``// Increment k by 1``                    ``k++;``                ``}``            ``}``        ``}``    ``}``}` `// Function to rearrange characters``// in a string so that no two``// adjacent characters are same``string rearrangeString(string& S, ``int` `N)``{` `    ``// If string is already valid``    ``if` `(isAdjChar(S) == ``false``) {``        ``return` `S;``    ``}` `    ``// If size of the string is 2``    ``if` `(S.size() == 2)``        ``return` `"-1"``;` `    ``// Function Call``    ``rearrangeStringUtil(S, N);` `    ``// Reversing the string``    ``reverse(S.begin(), S.end());` `    ``// Function Call``    ``rearrangeStringUtil(S, N);` `    ``// If the string is valid``    ``if` `(isAdjChar(S) == ``false``) {``        ``return` `S;``    ``}` `    ``// Otherwise``    ``return` `"-1"``;``}` `// Driver Code``int` `main()``{``    ``string S = ``"aaabc"``;``    ``int` `N = S.length();``    ``cout << rearrangeString(S, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;` `class` `GFG``{``    ``static` `char` `[]S = ``"aaabc"``.toCharArray();``  ` `// Function to check if a String S``// contains pair of adjacent``// characters that are equal or not``static` `boolean` `isAdjChar()``{``  ` `    ``// Traverse the String S``    ``for` `(``int` `i = ``0``; i < S.length - ``1``; i++)``    ``{` `        ``// If S[i] and S[i+1] are equal``        ``if` `(S[i] == S[i + ``1``])``            ``return` `true``;``    ``}` `    ``// Otherwise, return false``    ``return` `false``;``}` `// Function to rearrange characters``// of a String such that no pair of``// adjacent characters are the same``static` `void` `rearrangeStringUtil(``int` `N)``{``  ` `    ``// Initialize 3 variables``    ``int` `i = ``0``, j = ``1``, k = ``2``;` `    ``// Iterate until k < N``    ``while` `(k < N) {` `        ``// If S[i] is not equal``        ``// to S[j]``        ``if` `(S[i] != S[j]) {` `            ``// Increment i and j by 1``            ``i++;``            ``j++;` `            ``// If j equals k and increment``            ``// the value of K by 1``            ``if` `(j == k) {``                ``k++;``            ``}``        ``}` `        ``// Else``        ``else` `{` `            ``// If S[j] equals S[k]``            ``if` `(S[j] == S[k]) {` `                ``// Increment k by 1``                ``k++;``            ``}` `            ``// Else``            ``else` `{` `                ``// Swap``                ``swap(k,j);` `                ``// Increment i and j``                ``// by 1``                ``i++;``                ``j++;` `                ``// If j equals k``                ``if` `(j == k) {` `                    ``// Increment k by 1``                    ``k++;``                ``}``            ``}``        ``}``    ``}``}``static` `void` `swap(``int` `i, ``int` `j)``{``    ``char` `temp = S[i];``    ``S[i] = S[j];``    ``S[j] = temp; ``}``// Function to rearrange characters``// in a String so that no two``// adjacent characters are same``static` `String rearrangeString(``int` `N)``{` `    ``// If String is already valid``    ``if` `(isAdjChar() == ``false``) {``        ``return` `String.valueOf(S);``    ``}` `    ``// If size of the String is 2``    ``if` `(S.length == ``2``)``        ``return` `"-1"``;` `    ``// Function Call``    ``rearrangeStringUtil(N);` `    ``// Reversing the String``    ``reverse();` `    ``// Function Call``    ``rearrangeStringUtil(N);` `    ``// If the String is valid``    ``if` `(isAdjChar() == ``false``) {``        ``return` `String.valueOf(S);``    ``}` `    ``// Otherwise``    ``return` `"-1"``;``}``static` `void` `reverse() {``    ` `    ``int` `l, r = S.length - ``1``;``    ``for` `(l = ``0``; l < r; l++, r--) {``        ``char` `temp = S[l];``        ``S[l] = S[r];``        ``S[r] = temp;``    ``}``}``  ` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ` `    ``int` `N = S.length;``    ``System.out.print(rearrangeString(N));` `}``}` `// This code is contributed by Princi Singh`

## Python3

 `# Python 3 program for the above approach``S ``=` `"aaabc"` `# Function to check if a string S``# contains pair of adjacent``# characters that are equal or not``def` `isAdjChar(s):``  ` `    ``# Traverse the string S``    ``for` `i ``in` `range``(``len``(s)``-``1``):``      ` `        ``# If S[i] and S[i+1] are equal``        ``if` `(s[i] ``=``=` `s[i ``+` `1``]):``            ``return` `True` `    ``# Otherwise, return false``    ``return` `False` `# Function to rearrange characters``# of a string such that no pair of``# adjacent characters are the same``def` `rearrangeStringUtil(N):``    ``global` `S``    ``S ``=` `list``(S)``    ``# Initialize 3 variables``    ``i ``=` `0``    ``j ``=` `1``    ``k ``=` `2` `    ``# Iterate until k < N``    ``while` `(k < N):` `        ``# If S[i] is not equal``        ``# to S[j]``        ``if` `(S[i] !``=` `S[j]):` `            ``# Increment i and j by 1``            ``i ``+``=` `1``            ``j ``+``=` `1` `            ``# If j equals k and increment``            ``# the value of K by 1``            ``if` `(j ``=``=` `k):``                ``k ``+``=` `1` `        ``# Else``        ``else``:` `            ``# If S[j] equals S[k]``            ``if` `(S[j] ``=``=` `S[k]):` `                ``# Increment k by 1``                ``k ``+``=` `1` `            ``# Else``            ``else``:` `                ``# Swap``                ``temp ``=` `S[k]``                ``S[k] ``=` `S[j]``                ``S[j] ``=` `temp``                ``# Increment i and j``                ``# by 1``                ``i ``+``=` `1``                ``j ``+``=` `1` `                ``# If j equals k``                ``if` `(j ``=``=` `k):` `                    ``# Increment k by 1``                    ``k ``+``=` `1``    ``S ``=` `''.join(S)` `# Function to rearrange characters``# in a string so that no two``# adjacent characters are same``def` `rearrangeString(N):``    ``global` `S``    ` `    ``# If string is already valid``    ``if` `(isAdjChar(S) ``=``=` `False``):``        ``return` `S` `    ``# If size of the string is 2``    ``if` `(``len``(S) ``=``=` `2``):``        ``return` `"-1"` `    ``# Function Call``    ``rearrangeStringUtil(N)` `    ``# Reversing the string``    ``S ``=` `S[::``-``1``]``    ` `    ``# Function Call``    ``rearrangeStringUtil(N)` `    ``# If the string is valid``    ``if` `(isAdjChar(S) ``=``=` `False``):``        ``return` `S` `    ``# Otherwise``    ``return` `"-1"` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``N ``=` `len``(S)``    ``print``(rearrangeString(N))``    ` `    ``# This code is contributed by ipg2016107.`

## C#

 `// C# program for the above approach``using` `System;` `public` `class` `GFG``{``    ``static` `char` `[]S = ``"aaabc"``.ToCharArray();``  ` `// Function to check if a String S``// contains pair of adjacent``// characters that are equal or not``static` `bool` `isAdjChar()``{``  ` `    ``// Traverse the String S``    ``for` `(``int` `i = 0; i < S.Length - 1; i++)``    ``{` `        ``// If S[i] and S[i+1] are equal``        ``if` `(S[i] == S[i + 1])``            ``return` `true``;``    ``}` `    ``// Otherwise, return false``    ``return` `false``;``}` `// Function to rearrange characters``// of a String such that no pair of``// adjacent characters are the same``static` `void` `rearrangeStringUtil(``int` `N)``{``  ` `    ``// Initialize 3 variables``    ``int` `i = 0, j = 1, k = 2;` `    ``// Iterate until k < N``    ``while` `(k < N) {` `        ``// If S[i] is not equal``        ``// to S[j]``        ``if` `(S[i] != S[j]) {` `            ``// Increment i and j by 1``            ``i++;``            ``j++;` `            ``// If j equals k and increment``            ``// the value of K by 1``            ``if` `(j == k) {``                ``k++;``            ``}``        ``}` `        ``// Else``        ``else` `{` `            ``// If S[j] equals S[k]``            ``if` `(S[j] == S[k]) {` `                ``// Increment k by 1``                ``k++;``            ``}` `            ``// Else``            ``else` `{` `                ``// Swap``                ``swap(k,j);` `                ``// Increment i and j``                ``// by 1``                ``i++;``                ``j++;` `                ``// If j equals k``                ``if` `(j == k) {` `                    ``// Increment k by 1``                    ``k++;``                ``}``            ``}``        ``}``    ``}``}``static` `void` `swap(``int` `i, ``int` `j)``{``    ``char` `temp = S[i];``    ``S[i] = S[j];``    ``S[j] = temp; ``}``  ` `// Function to rearrange characters``// in a String so that no two``// adjacent characters are same``static` `String rearrangeString(``int` `N)``{` `    ``// If String is already valid``    ``if` `(isAdjChar() == ``false``) {``        ``return` `String.Join(``""``,S);``    ``}` `    ``// If size of the String is 2``    ``if` `(S.Length == 2)``        ``return` `"-1"``;` `    ``// Function Call``    ``rearrangeStringUtil(N);` `    ``// Reversing the String``    ``reverse();` `    ``// Function Call``    ``rearrangeStringUtil(N);` `    ``// If the String is valid``    ``if` `(isAdjChar() == ``false``) {``        ``return` `String.Join(``""``,S);``    ``}` `    ``// Otherwise``    ``return` `"-1"``;``}``static` `void` `reverse() {``    ` `    ``int` `l, r = S.Length - 1;``    ``for` `(l = 0; l < r; l++, r--) {``        ``char` `temp = S[l];``        ``S[l] = S[r];``        ``S[r] = temp;``    ``}``}``  ` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ` `    ``int` `N = S.Length;``    ``Console.Write(rearrangeString(N));` `}``}` `// This code is contributed by shikhasingrajput`
Output:
`acaba`

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

My Personal Notes arrow_drop_up