StackEasy

Remove Adjacent Duplicates Visualizer

What is Remove Adjacent Duplicates

Repeatedly delete two adjacent letters that are the same. Return the letters that remain, left to right.

Approach

One pass is enough. Cancelling a pair can expose an older letter, and the stack top is exactly that letter.

Visualization & algorithm

Letters cancelling on the stack
for each letter:
if top is the same letter: pop
else: push
join the stack
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each letter is pushed and popped at most once.
SpaceO(n)A string with no pairs keeps every letter.

Implementation

def solve(self, s):
    st = []
    for ch in s:
        if st and st[-1] == ch:
            st.pop()
        else:
            st.append(ch)
    return ''.join(st)