Removing adjacent duplicates from a string in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

JavaScript function that takes in a string, str, as the first and the only argument.

A duplicate removal consists of choosing two adjacent and equal letters, and removing them.

We repeatedly make duplicate removals on string str until we no longer can.

And our function should finally return the final string after all such duplicate removals have been made.

For example, if the input to the function is −

const str = 'kllkmk';

Then the output should be −

const output = 'mk';

Output Explanation:

Firstly, we will remove ‘ll’ from the string to reduce it to ‘kkmk’, then after removing ‘kk’, we will return the new string.

Example

The code for this will be −

 Live Demo

const str = 'kllkmk';
const removeDuplicates = (str = '') => {
   const arr = [];
   for(const char of str){
      if(char === arr[arr.length - 1]){
         while(arr[arr.length - 1] === char){
            arr.pop();
         };
      } else {
         arr.push(char);
      };
   };
   return arr.join('');  
};
console.log(removeDuplicates(str));

Output

And the output in the console will be −

mk
raja
Published on 07-Apr-2021 11:34:03
Advertisements