Design Gurus Logo
Remove All Adjacent Duplicates in String II (medium)

Problem Statement

You are given a string s and an integer k. Your task is to remove groups of identical, consecutive characters from the string such that each group has exactly k characters. The removal of groups should continue until it's no longer possible to make any more removals. The result should be the final version of the string after all possible removals have been made.

Examples

    • Input: s = "abbbaaca", k = 3
    • Output: "ca"
    • Explanation: First, we remove "bbb" to get "aaaca". Then, we remove "aaa" to get "ca".
    • Input: s = "abbaccaa", k = 3
    • Output: "abbaccaa"
    • Explanation: There are no instances of 3 adjacent characters being the same.
    • Input: s = "abbacccaa", k = 3
    • Output: "abb"
    • Explanation: First, we remove "ccc" to get "abbaaa". Then, we remove "aaa" to get "abb".

A note on the pattern. Like the previous question, this one uses a stack without keeping it in any sorted order, so it is not strictly a monotonic stack question either. What carries over is the shape: look at the top, decide, and pop when a condition holds. Here the stack holds a character together with how many times it has repeated, which is the first step toward storing more than a bare value on the stack.

Constraints:

  • 1 <= s.length <= 10<sup>5</sup>
  • 2 <= k <= 10<sup>4</sup>
  • s only contains lowercase English letters.

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory