Limiting duplicate character occurrence to once in JavaScript


Problem

We are required to write a JavaScript function that takes in a string, str, as the only argument.

The function should prepare a new string based on the input string in which the only one appearance of each character is kept and the character kept is the one which makes the result string lexicographically the smallest.

For example, if the input to the function is −

const str = 'cbacdcbc';

Then the output should be −

const output = 'acdb';

Output Explanation:

Note that we could have removed any occurrence of ‘c’ from the string but we removed the very first, which makes the string lexicographically the smallest and same in case of ‘a’ and ‘b’.

Example

The code for this will be −

const str = 'cbacdcbc';
const removeDuplicates = (str = '') => {
   if (str.length <= 1) {
      return str;
   };
   let flag;
   let string = "";
   let legend = new Array(26).fill(-1 let last = "z";
   let ind = 0;
   for (let i = str.length - 1; i > -1; i--) {
      const element = str[i];
      if (legend[element.charCodeAt() - 97] < 0) {
         legend[element.charCodeAt() - 97] = i;
         last = element;
         ind = i;
         string += element;
      } else {
         if (last >= element) {
            last = element;
            ind = i;
         }
      }
   }
   let finalStr = last;
   while (string.length > finalStr.length) {
      legend.fill(-1);
      for (let i = str.length - 1; i > ind; i--) {
         const element = str[i];
         if (finalStr.indexOf(element) < 0) {
            if (legend[element.charCodeAt() - 97] < 0) {
               legend[element.charCodeAt() - 97] = i;
               last = element;
               flag = i;
            } else {
               if (last >= element) {
                  last = element;
                  flag = i;
               }
            }
         }
      }
      ind = flag;
      finalStr += last;
   }
   return finalStr;
};
console.log(removeDuplicates(str));

Code Explanation:

The idea here is −

For the first time, we loop through the whole string to check which letters are used, and find the smallest beginning letter substring that contains all characters.

This is easier to understand if we start the loop from right to left and memorize the starting position of the substring, and the beginning minimal letter.

Then we start looping the substring (without the beginning minimal letter), still from right to left, but this time we need to ignore the letters that we already stored.

Output

And the output in the console will be −

acdb

Updated on: 20-Mar-2021

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements