Remove All Adjacent Duplicates In String — LeetCode 1047 Python Solution

EasyStackString
Problem
#1047
Pattern
Stack
Reading time
2 min

The problem

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

Example

Input
s = "abbaca"
Output
"ca"
Explanation
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Python solution

Python
class Solution:
    def removeDuplicates(self, s: str) -> str:
        stk = []
        for c in s:
            if stk and stk[-1] == c:
                stk.pop()
            else:
                stk.append(c)
        return ''.join(stk)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1047. Remove All Adjacent Duplicates In String 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 1047. Remove All Adjacent Duplicates In String?
LeetCode 1047. Remove All Adjacent Duplicates In String is rated Easy on LeetCode.
What is the time complexity of LeetCode 1047. Remove All Adjacent Duplicates In String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1047. Remove All Adjacent Duplicates In String?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1047. Remove All Adjacent Duplicates In String cover?
LeetCode 1047. Remove All Adjacent Duplicates In String 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