Given a string of ‘0’, ‘1’ and ‘2’. The task is to find the minimum number of replacements such that the adjacent characters are not equal.
Input: s = “201220211”
Resultant string after changes is 201210210
Input: s = “0120102”
Approach: The following problem can be solved using greedy method. We can greedily compare every adjacent pair. If the adjacent pairs which is character at ith and i-1th are same, then replace ith th character with a character which is not equal to the character at i-1th and i+1th index. In case of the last adjacent pair, just replace it with the character which is not equal to the character at i-1th index.
Below is the implementation of the above approach:
Time Complexity : O(n)
- Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
- Minimum number of replacements to make the binary string alternating | Set 2
- Minimum characters to be added at front to make string palindrome
- Minimum number of characters to be removed to make a binary string alternate
- Minimum replacements such that the difference between the index of the same characters is divisible by 3
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Covert string X to an anagram of string Y with minimum replacements
- String with k distinct characters and no same characters adjacent
- Min flips of continuous characters to make all characters same in a string
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Rearrange characters in a string such that no two adjacent are same
- Minimum operations to make frequency of all characters equal K
- Missing characters to make a string Pangram
- Make a string from another by deletion and rearrangement of characters
- Minimum deletions from string to reduce it to string with at most 2 unique 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 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.