Remove All Adjacent Duplicates In String

Try to solve the Remove All Adjacent Duplicates In String problem.

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:

  • 11 \leq string.length 103\leq 10^3
  • string consists of lowercase English alphabets.

Examples#

Created with Fabric.js 3.6.6 Input string a a a Input a a a a Sample example 1 Remove adjacent duplicates that are highlighted. All adjacent duplicates are removed from the string. Output

1 of 3

Created with Fabric.js 3.6.6 Input Remove adjacent duplicates that are highlighted. All adjacent duplicates are removed from the string. Sample example 2 Input string a b b a a c a a b b a a c a a c a Output

2 of 3

Created with Fabric.js 3.6.6 Input Remove adjacent duplicates that are highlighted. All adjacent duplicates are removed from the string. Sample example 3 Input string s a d k k d a s s a s a d k k d a s s a s a d d a a Remove adjacent duplicates that are highlighted. s a Output

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Remove All Adjacent Duplicates In String

1

What will be the output after removing all adjacent duplicates from the string given below?

string = “azxxzy”

A)

azzy

B)

axxy

C)

ay

D)

" "

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Initialize a stack to store characters. Traverse every character in the string.

In each iteration, if the string character is same as the character at the top of the stack, pop the character from the stack.

If the string character is different from the character at the top of the stack, push that character into the stack.

After all iterations, form a string from the characters in the stack and return that string.


Try it yourself#

Implement your solution in the following coding playground.

Python
usercode > main.py
Input #1
Remove All Adjacent Duplicates In String

Stacks: Introduction

Solution: Remove All Adjacent Duplicates In String