Minimum replacements such that no palindromic substring of length exceeding 1 is present in the given string
Given a string str consisting of lowercase characters, the task is to modify the string such that it does not contain any palindromic substring of length exceeding 1 by minimum replacement of characters.
Input: str = “bbbbbbb”
String can be modified to “bacbacb” by replacing 4 characters.
Input: str = “geeksforgeeks”
To solve the problem, the idea is that, if there exists a palindrome of length larger than 3, then there exists a palindrome of length 2 or 3. Therefore, greedily remove all palindromes of length 2 or 3. Follow the steps below to solve the problem:
- Initialize a variable, say change, to store the required number of replacements.
- Iterate over the characters of the given string and perform the following steps:
- If the character at the current index is the same as the character at the next index, then increment change by 1.
- Otherwise, check if the character at the previous index is the same as the character at the next index, i.e. there is a palindromic substring of length 3. Therefore, increment change by 1.
Below is the implementation of the above approach:
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time
Auxiliary Space: O(1), as we are not using any extra space.