Problem Description
You are given a string s
and an integer k
, a k
duplicate removal consists of choosing k
adjacent and equal letters from s
and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k
duplicate removals on s
until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.
Key Insights
- The problem involves removing groups of adjacent characters that occur
k
times or more. - A stack can be effectively used to keep track of characters and their counts, allowing for easy removal when the count reaches
k
. - We need to iterate through the string while maintaining the order of characters that do not form a group of
k
.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string s
. Each character is processed at most twice.
Space Complexity: O(n), in the worst case, for the stack used to store the characters and their counts.
Solution
We will use a stack to keep track of characters and their consecutive counts. As we iterate through the characters of the string, we will:
- Push characters onto the stack alongside their counts.
- If the count of a character reaches
k
, we will pop it off the stack. - At the end of the iteration, we will rebuild the string from the stack.
This approach efficiently handles the duplicate removal while ensuring we only traverse the string a limited number of times.