Early Access: 87 spots left.

Claim
Coding Interview PatternsStacksRemove All Adjacent Duplicates In String

Problems

Remove All Adjacent Duplicates In String

Easy·Tagsstringstack

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.

Examples

Example 1
Input
s: "abbaca"
Output
"\"ca\""
Why
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".
Example 2
Input
s: "azxxzy"
Output
"\"ay\""
Why
Remove "xx" to get "azzy", then remove "zz" to get "ay".
Example 3
Input
s: "a"
Output
"\"a\""
Why
No adjacent duplicates exist.

Constraints

  • 1 <= s.length <= 100000
  • s consists of lowercase English letters.

Hints

Stuck? Reveal a nudge toward the right pattern, one step at a time.

Hint 1
If you use a brute-force approach of scanning the string and replacing adjacent characters, you will have to re-scan the string from the beginning every time a replacement is made. This is too slow.
Hint 2
Instead, process the string from left to right while keeping track of the characters you've seen so far in a Stack.
Hint 3
When you process a new character, compare it to the top of the Stack. If it matches, what should you do? Pop the stack! If it doesn't match, push the new character.
Hint 4
At the very end, the Stack will contain only the characters that could not be matched and removed.