Remove All Adjacent Duplicates In String

Easy

Topics
StringStack

Given a string s, repeatedly remove two adjacent equal letters until no more can be removed. Return the final string.

Example 1

inabbaca
outca
removed
A removal can expose a new adjacent pair, so one scan of the original string is not enough. A stack handles the cascade naturally: push each character unless it equals the top, in which case pop instead. What is left is ca.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "abbaca"
Output: "ca"

Example 2

inazxxzy
outay
removed
Input:  s = "azxxzy"
Output: "ay"

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Removing a pair can expose a new adjacent pair — "abba" loses bb, bringing the two as together, and they must go too. Rescanning the string after each removal is correct and O(n^2).

A stack collapses the cascade into one pass. Push each character, but first check whether it matches the current top; if it does, pop instead. The next character is then compared against the new top, which is the cascade handled automatically.

Approach

  1. For each character: if the stack is non-empty and its top equals the character, pop; otherwise push.
  2. Join the stack.

Dry Run

s = "abbaca"

a   stack empty      push    [a]
b   top a, differs   push    [a,b]
b   top b, matches   pop     [a]
a   top a, matches   pop     []
c   stack empty      push    [c]
a   top c, differs   push    [c,a]

answer "ca"

note the cascade: removing bb is what made the two a's
adjacent, and the stack caught it with no second pass

Complexity

  • Time — O(n): each character pushed at most once and popped at most once. Against O(n^2) for repeated rescanning.
  • Space — O(n): the stack, which holds the whole string when nothing cancels.

Common Pitfalls

  • Popping without first checking the stack is non-empty.
  • Rescanning from the start after each removal, which is the quadratic version.
  • Removing all duplicates rather than adjacent pairs. "aba" is unchanged — the two as are not adjacent.
  • Deleting more than two at a time. The rule removes exactly a pair, so "aaa" leaves one a, not none.

Full Solution — all languages

class Solution:
    def removeDuplicates(self, s):
        stack = []
        for c in s:
            if stack and stack[-1] == c:
                stack.pop()
            else:
                stack.append(c)
        return "".join(stack)
Asked at Paytm
SensAI
Beta
Tap the mic to stop voice mode