Since we want to remove all adjacent duplicates with length k, we can use a stack, and count the current length of the run. Each item in the stack has the character as well as its previous occurrences. If it occurs k times, pop it from the stack.
At the end, we rejoin the string at the end for each character along with its occurrences, since they didn’t show up enough times to be removed
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = [['', 0]]
for c in s:
if c == stack[-1][0]:
stack[-1][1] += 1
if stack[-1][1] == k:
stack.pop()
else:
stack.append([c, 1])
return "".join(char * n for char, n in stack)