LC 1209 [M] Remove All Adjacent Duplicates in String II - ALawliet/algorithms GitHub Wiki

class Solution:
    def removeDuplicates(self, s: str, k: int) -> str:
        stack = ['#', 0](/ALawliet/algorithms/wiki/'#',-0) # stack of char:freq pairs, dummy pair to avoid empty stack

        for c in s:
            if stack[-1][0] == c: # (if stack is not empty and) same char => increment count
                stack[-1][1] += 1

                if stack[-1][1] == k: # max duplicates => remove
                    stack.pop()

            else: # diff char => push
                stack.append([c, 1])

        return ''.join([c * freq for c, freq in stack])