Given a string ‘str’ and an integer ‘k’, the task is to reduce the string by applying the following operation:
Choose a group of ‘k’ consecutive identical characters and remove them. The operation can be performed any number of times until it is no longer possible.
Finally, print the reduced string.
Input: k = 2, str = “geeksforgeeks”
After the removal of 2 consecutive “e” twice,
the string will get reduced to “gksforgks”.
Input: k = 3, str = “qddxxxd”
Removal of “xxx” gives “qddd”.
Again, removal of “ddd” gives the final string “q”
Approach: This problem can be solved using the data structure, Stack.
- Maintain a stack of the characters while iterating through them one by one.
- When there are ‘k’ identical characters at the top of the stack, pop them out of the stack.
- To implement this, every element of the stack will be a pair of character and it’s consecutive frequency. If the character to be pushed is different from the character which is currently at the top of the stack then it’s frequency will be set to “1”.
- Else, if the character is identical to the character at the top of the stack then it’s frequency will be one greater than the frequency of the element at the top of the stack.
- In the end, the characters which are left in the stack will form the resultant string.
Below is the implementation of the above approach:
Time Complexity – O(N)
Each element gets pushed into stack only once.
- Minimum deletions from string to reduce it to string with at most 2 unique characters
- Ways of transforming one string to other by removing 0 or more characters
- Minimum sum of squares of character counts in a given string after removing k characters
- Group consecutive characters of same type in a string
- Least number of manipulations needed to ensure two strings have identical characters
- Recursive program to insert a star between pair of identical characters
- Reduce Hamming distance by swapping two characters
- Removing row or column wise duplicates from matrix of characters
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Print consecutive characters together in a line
- Min flips of continuous characters to make all characters same in a string
- String with k distinct characters and no same characters adjacent
- Minimum reduce operations to covert a given string into a palindrome
- Removing punctuations from a given string
- Removing spaces from a string using Stringstream
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.