The name of the problem I picked from LeetCode for this week is “Remove All Adjacent Duplicates In String”.

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".

Below is another example showing how to process while working on this problem:

Image for post

The giving string in the example is ‘mppmhkkl’ and the answer is ‘hl’. First, the duplicate ‘pp’ is deleted, then ‘mm’ is removed, and finally ‘kk’ is deleted to get the result. The string left after removing all of the adjacent duplicates is ‘hl’. Note that you only delete two at a time.


My Solution in JavaScript

My approach was to use a stack data structure to solve this problem. I will follow these steps to implement it:

  1. Create an empty stack array.
  2. Iterate through the input string.
  3. Check at each iteration if the top (last) element of the stack is equal to the current element of the input string.
  4. If true, remove the top element of the stack.
  5. If not, add the current element of the string on top of the stack.
  6. Return all elements of the stack as a string after joining them.

#algorithms #javascript #programming #stack #ruby

Remove Adjacent Duplicates Problem
1.75 GEEK