# Solution: Remove All Adjacent Duplicates In String

Let's solve the Remove All Adjacent Duplicates In String problem using the Stacks pattern.

We'll cover the following

## Statement

You are given a string consisting of lowercase English letters. Repeatedly remove adjacent duplicate letters, one pair at a time. Both members of a pair of adjacent duplicate letters need to be removed.

Constraints:

• $1 \leq$ string.length $\leq 10^3$
• string consists of lowercase English alphabets.

## Solution

So far, youâ€™ve probably brainstormed some approaches and have an idea of how to solve this problem. Letâ€™s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.

### Naive approach

The naive approach is to generate a set of all possible adjacent duplicates in a string of small English alphabets, that is, {"aa", "bb", "cc", "dd", ...}. Traverse over the string to see if such duplicates are present. Weâ€™ll use nested loops to check this condition. If duplicate characters are found, weâ€™ll remove the adjacent duplicates from the input string. For example, in the "abaac" string, weâ€™ll remove "aa" from the string, which results in "abc".

Since weâ€™re using nested loops, the time complexity of this approach is $O(n^2)$, which is not optimal. Letâ€™s see if we can use the stacks pattern to reduce the time complexity of our solution.

### Optimized approach using stacks

We can remove adjacent duplicates in pairs, which is similar to matching opening and closing parentheses. In such problems, we typically use stacks to store intermediate results to deal with nested pairs of parentheses. Weâ€™ll use the same concept here.

Weâ€™ll initialize a stack first. Then, weâ€™ll iterate the complete string from left to right, and for every character, weâ€™ll check the following:

• If the stack is empty, weâ€™ll push the character onto the stack.
• If the stack is not empty, weâ€™ll perform the following tasks:
• If the stringâ€™s character is different from the stackâ€™s top character, weâ€™ll push the stringâ€™s character onto the stack because we did not find the adjacent duplicate.
• If the stringâ€™s character is the same as the stackâ€™s top character, it means that we found the adjacent duplicate characters. Weâ€™ll pop that character from the stack and move to the next character in the string.
• After the entire string has been traversed, the remaining characters in the stack will be our result. Weâ€™ll form a string from those characters and return it.

The slides below illustrate how weâ€™d like the algorithm to run:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.