## Similar Problems

Similar Problems not available

# Remove All Adjacent Duplicates In String - Leetcode Solution

LeetCode: Remove All Adjacent Duplicates In String Leetcode Solution

Difficulty: Easy

Problem: Given a string S of lowercase 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 is guaranteed the answer is unique.

Example: Input: "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".

Solution: We can solve this problem by using a stack data structure. We will iterate through each character of the input string and compare it with the top element of the stack. If they are equal, we will pop the element from the stack. Otherwise, we will push the character onto the stack. The final string will be the elements of the stack concatenated in reverse order.

Algorithm:

- Initialize an empty stack
- Iterate through each character of the input string: a. If the stack is empty or the top element of the stack is not equal to the current character, push the character onto the stack b. Otherwise, pop the top element of the stack
- Concatenate the elements of the stack in reverse order to form the final string
- Return the final string

Python code:

class Solution: def removeDuplicates(self, S: str) -> str: stack = [] for c in S: if stack and stack[-1] == c: stack.pop() else: stack.append(c) return ''.join(stack[::-1])

## Remove All Adjacent Duplicates In String Solution Code

`1`