Skip to content

visual walkthrough

Remove All Adjacent Duplicates In String

EasyStack SimulationReported at: MetaAmazon

Using the stack as a 'last kept character' buffer.

Solve on LeetCode

The idea

When two equal letters cancel, the letters on either side may become neighbours and cancel too. A stack handles this naturally: its top is always the letter just before the one being read.

Compare each new letter with the top: equal means cancel (pop), otherwise push.

Complexity

approachtimespace
Rescan after each deletionO(n²)O(n)
StackO(n)O(n)

More walkthroughs