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
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Ways of transforming one string to other by removing 0 or more characters
- Check if string remains palindrome after removing given number of 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
- Reduce the number to minimum multiple of 4 after removing the digits
- Least number of manipulations needed to ensure two strings have identical characters
- Recursive program to insert a star between pair of identical characters
- Minimum characters that are to be inserted such that no three consecutive characters are same
- Reduce Hamming distance by swapping two characters
- Removing row or column wise duplicates from matrix of characters
- Print consecutive characters together in a line
- Longest substring such that no three consecutive characters are same
- Permutation of a string with maximum number of characters greater than its 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 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.