Given a string S, change the smallest number of letters in S such that all adjacent characters are different. Print the resultant string.
Input : S = "aab" Output: acb Explanation : Loop will start for i-th character, which is second ‘a’. It’s cannot be ‘b’ since it matches with third char. So output should be ‘acb’. Input : S = "geeksforgeeks" Output: geaksforgeaks Explanation : Resultant string, after making minimal changes. S = "geaksforgeaks". We made two changes, which is the optimal solution here.
We can solve this problem using greedy approach. Let us consider a segment of length k of consecutive identical characters. We have to make at least [K/2] changes in the segment, to make that there are no identical characters in a row. We can also change the second, fourth etc.. characters of the string that is it should not be equal to the letter on the left side and the letter to the right side.
Traverse the string from starting index (i = 1) and if any two adjacent letters( i & i-1) are equal then initialize (i)th character with ‘a’ and start another loop to make (i)th character different from the left and right letters.
Below is the implementation of above approach :
- Print all the duplicates in the input string
- Recursively remove all adjacent duplicates
- Print distinct sorted permutations with duplicates allowed in input
- Remove duplicates from a given string
- Remove three consecutive duplicates from string
- Remove all consecutive duplicates from the string
- Remove all duplicates from a given string in Python
- Character replacement after removing duplicates from a string
- Remove duplicates from a string in O(1) extra space
- Distinct permutations of a string containing duplicates using HashSet in Java
- 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
- C program to swap adjacent characters of a String
- Print shortest path to print a string on screen
- Smallest length string with repeated replacement of two distinct adjacent
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.