Remove All Adjacent Duplicates In String
Stack Cancels Pairs
Asked at 12 companies
4 recent
- Whatnot
- Amazon
- Bloomberg
- Grammarly
- Paytm
- Ripple
- Geico
- Meta
- Deloitte
+2 moreShow fewer
- Apple
- Cisco
Community-reported · source · updated 2026-11-18. ● asked in the last 6 months.
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 110 pointsSolved (Easy) 0/20Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Watch the concept video if the pattern is new to you.
Step 2
Try it on paper
5–10 minutes, no code yet
ProblemProblem statementYou are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.ReadHide
Problem Statement
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.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
""" + PROV + r"""
Input / Output
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".
Input: s = "azxxzy"
Output: "ay"
Code it on LeetCode
There's no editor for this one here yet, so solve it on LeetCode, with its own tests. Then tick My code passed below, and it joins your reviews. With your LeetCode account linked, that happens on its own.
An error or a Wrong Answer there? What each one means.
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code
Approach
Pattern Recognition
A stack cancels pairs — removing a pair can bring two previously-separated letters together and make a new pair, so the only thing that matters is the last surviving letter. Keep a stack of survivors: if the next letter matches the top, both vanish; otherwise push it. One pass, no rescans.
Approach
Brute Force — Rescan Until Stable, O(n^2)
changed = True
while changed:
changed = False
scan s, delete every adjacent equal pair in one pass
if any pair was deleted: changed = True
Correct, but each pass can delete only the pairs visible right now, and a deletion can create a new pair — so the string may need many passes.
Optimized — Stack, O(n)
stack = []
for ch in s:
if stack and stack[-1] == ch:
stack.pop() # pair cancels
else:
stack.append(ch)
return ''.join(stack)
Example: "abbaca" — push a, b; next b matches the top, pop it; next a matches the new top a, pop it; push c, a → "ca".
Complexity
| Approach | Time | Space | Notes |
|---|---|---|---|
| Rescan until stable | O(n^2) | O(n) | Each deletion can force another full pass |
| Stack | O(n) | O(n) | One pass; the top of the stack is all history |
Solution code
class SolutionBruteForce:
"""O(n^2) time | O(n) space — rescan and delete pairs until nothing changes."""
def removeDuplicates(self, s: str) -> str:
changed = True
while changed:
changed = False
out = []
i = 0
while i < len(s):
if i + 1 < len(s) and s[i] == s[i + 1]:
i += 2
changed = True
else:
out.append(s[i])
i += 1
s = "".join(out)
return s
class Solution:
"""O(n) time | O(n) space — stack: a matching top cancels the pair."""
def removeDuplicates(self, s: str) -> str:
stack = []
for ch in s:
if stack and stack[-1] == ch:
stack.pop()
else:
stack.append(ch)
return "".join(stack)Other ways to solve it
- Community solutions on LeetCode ↗ for many more versions, in many languages. Read them after you've solved it.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language