Remove All Adjacent Duplicates In String

Solution For Remove All Adjacent Duplicates In String

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:
1. Initialize an empty stack
2. 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
3. Concatenate the elements of the stack in reverse order to form the final string
4. 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])

Step by Step Implementation For Remove All Adjacent Duplicates In String

public String removeDuplicates(String S) {
        Stack stack = new Stack<>();
        for (char c : S.toCharArray()) {
            if (!stack.empty() && stack.peek() == c) {
                stack.pop();
            } else {
                stack.push(c);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (char c : stack) {
            sb.append(c);
        }
        return sb.toString();
    }
class Solution:
    def removeDuplicates(self, S: str) -> str:
        # Base case
        if len(S) == 0:
            return S
        
        # Recursive case
        else:
            # If the first two characters are the same, 
            # we can remove them and make a recursive call
            if S[0] == S[1]:
                return self.removeDuplicates(S[2:])
            
            # If the first two characters are not the same, 
            # we keep the first character and make a recursive call
            # on the rest of the string
            else:
                return S[0] + self.removeDuplicates(S[1:])
var removeDuplicates = function(s) {
    
    // create a stack to store characters
    let stack = [];
    
    // loop through string
    for (let i = 0; i < s.length; i++) {
        
        // get current character
        let c = s.charAt(i);
        
        // if stack is empty or character at top of stack is not equal to current character, push current character to stack
        if (stack.length === 0 || stack[stack.length - 1] !== c) {
            stack.push(c);
        } else {
            // else, pop character from stack
            stack.pop();
        }
    }
    
    // return stack as string
    return stack.join("");
    
};
One possible solution to this problem is to use a stack data structure to keep track of the characters in the string. We can iterate through the string, and if the character we are currently looking at is not the same as the top element of the stack, we can push it onto the stack. If the character is the same as the top element of the stack, we can pop the top element off the stack. We can continue doing this until we have iterated through the entire string. The characters remaining in the stack will be the characters that are not adjacent duplicates.
public class Solution {
    public string RemoveDuplicates(string s) {
        // create a stack to store the characters in the string
        Stack stack = new Stack();
        
        // loop through each character in the string
        foreach (char c in s) {
            // if the stack is empty or the top character of the stack is not equal to the current character
            if (stack.Count == 0 || stack.Peek() != c) {
                // push the current character onto the stack
                stack.Push(c);
            } else {
                // if the top character of the stack is equal to the current character
                // pop the top character off the stack
                stack.Pop();
            }
        }
        
        // return the remaining characters in the stack as a string
        return new string(stack.ToArray());
    }
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]