Formatting a string to separate identical characters in JavaScript


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

The function should try and re-organize the characters present in the string such that no two identical characters are placed adjacent to each other.

If there exists at least one such combination then our function should return that combination string otherwise our function should return an empty string.

For example −

If the input string is −

const str = 'add';

Then our function can output −

const output = 'dad';

Example

Following is the code −

const str = 'add';
const formatString = (str = '') => {
   const map = {};
   for(let i = 0; i < str.length; i++){
      map[str[i]] = map[str[i]] || 0;
      map[str[i]] ++;
   }
   let keys = Object.keys(map).sort((a, b) => {
      if(map[a] < map[b]){
         return 1;
      };
      return -1;
   });
   let flag = str.length%2?(Math.floor(str.length/2)+1):str.length/2;
   if(map[keys[0]] > flag){
      return "";
   };
   const res = [];
   let index = 0, max = str.length-1;
   while(keys.length){
      let currKey = keys.shift();
      let count = map[currKey];
      while(count){
         res[index] = currKey;
         index = index+2;
         if(index>max)
            index=1;
         count--;

      }
   }
   return res.join("");
};
console.log(formatString(str));

Output

Following is the console output −

dad

Updated on: 18-Jan-2021

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements