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
- Print all distinct permutations of a given string with duplicates
- Recursively remove all adjacent duplicates
- Python | Program to print duplicates from a list of integers
- Remove duplicates from a given string
- Print distinct sorted permutations with duplicates allowed in input
- Remove all consecutive duplicates from the string
- Remove all duplicates from a given string in Python
- Remove three consecutive duplicates from string
- Character replacement after removing duplicates from a string
- Remove duplicates from a string in O(1) extra space
- Rearrange characters in a string such that no two adjacent are same
- Efficiently check if a string has duplicates without using any additional data structure
- Smallest length string with repeated replacement of two distinct adjacent
- Reduce string to shortest length by deleting a pair of same adjacent characters
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.