Remove All Adjacent Duplicates in String II — LeetCode 1209 Python Solution

MediumStackString
Problem
#1209
Pattern
Stack
Reading time
2 min

The problem

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.

Example

Input
s = "abcd", k = 2
Output
"abcd"
Explanation
There's nothing to delete.

Python solution

Python
class Solution:
    def removeDuplicates(self, s: str, k: int) -> str:
        stk = []
        for c in s:
            if stk and stk[-1][0] == c:
                stk[-1][1] = (stk[-1][1] + 1) % k
                if stk[-1][1] == 0:
                    stk.pop()
            else:
                stk.append([c, 1])
        ans = [c * v for c, v in stk]
        return "".join(ans)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1209. Remove All Adjacent Duplicates in String II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1209. Remove All Adjacent Duplicates in String II?
LeetCode 1209. Remove All Adjacent Duplicates in String II is rated Medium on LeetCode.
What is the time complexity of LeetCode 1209. Remove All Adjacent Duplicates in String II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1209. Remove All Adjacent Duplicates in String II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1209. Remove All Adjacent Duplicates in String II cover?
LeetCode 1209. Remove All Adjacent Duplicates in String II is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview