Remove Adjacent Duplicates Problem

Solved in JavaScript and Ruby using Stack

Bahay Gulle Bilgi
The Startup

--

Photo by Eaters Collective on Unsplash

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:

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

--

--