Maximum count of X that can be inserted with no 3 adjacent characters are X
Given a string, str of length N and a character X, the task is to find the maximum count of characters X that are to be inserted into the string such that no three consecutive characters are equal to X. If it is not possible to find such a string, then print -1.
Input: str = “xxyxy”, X = X
Insert an ‘x’ at position 4: “xxyxxy”.
Insert two ‘x’ at position 7: “xxyxxyxx”
Now no more ‘x’ can be inserted, as it will lead to a size 3 substring with all x in it.
Hence the required count is 3.
Input:str = “gfg”, X = ‘X’
Approach: The idea is to count all the positions where X can be inserted and then subtract the count of already present X in the string.
Below are the steps:
- The maximum number of X that can be inserted in the string is 2 * (N + 1) characters as it is possible to insert two X at the start and end of the string and between every consecutive character.
- Now, find the number of groups of consecutive X having a size of 1 or 2 and store it in a variable countX.
- The number of X that can be inserted in the given string is 2 * (number of places to be inserted + 1) – number of found Xs.
- In conclusion, a simple mathematical formula, 2 * (N + 1) – (N – Xs) can be used to find the final answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
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.