Encoding string based on character frequency in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

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

Our function should create a new string based on the input string where each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string.

And we should ignore capitali

For example, if the input to the function is −

Input

const str = 'Success';

Output

const output = ')())())';

Example

Following is the code −

 Live Demo

const str = 'Success';
const mapString = (str = '') => {
   const mainStr = str.toLowerCase()
   const hash = {}
   let res = ''
   for (let char of mainStr) {
      hash[char] = ~~hash[char] + 1
   }
   for (let char of mainStr) {
      if (hash[char] > 1) {
      res += ')'
   } else {
      res += '('
   }
}
   return res
};
console.log(mapString(str));

Output

)())())
raja
Published on 22-Apr-2021 10:48:43
Advertisements