VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reduce-the-string-by-removing-k-consecutive-identical-characters/

⇱ Reduce the string by removing K consecutive identical characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reduce the string by removing K consecutive identical characters

Last Updated : 23 Apr, 2025

Given a string str and an integer k, the task is to reduce the string by applying the following operation any number of times until it is no longer possible:

Choose a group of k consecutive identical characters and remove them from the string.

Finally, print the reduced string.

Examples:

Input: K = 2, str = "geeksforgeeks" 
Output: gksforgks 
Explanation: After removal of both occurrences of the substring "ee", the string reduces to "gksforgks".

Input: K = 3, str = "qddxxxd" 
Output:
Explanation: Removal of "xxx" modifies the string to "qddd". Again, removal of "ddd" modifies the string to "q". 

Approach: Using a Stack of Pairs - O(n) time and O(n) space

The approach uses a stack to track characters and their consecutive occurrences. As the string is processed, characters are pushed onto the stack with a count of consecutive occurrences. If a character repeats k times, it is skipped. After processing, the remaining characters in the stack are used to build the result string, which is then reversed to maintain the correct order.


Output
gksforgks

Approach: Using a Single Stack - O(n) time and O(n) space

The approach uses a stack to remove consecutive characters that appear exactly k times. As we iterate through the string, we push each character onto the stack. If the top of the stack matches the current character, we increment a count. When the count reaches k, the characters are effectively removed. After processing the string, the remaining characters in the stack are popped and concatenated to form the final result.


Output
gksforgks
Comment
Article Tags:
Article Tags: