Placing same string characters apart in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of characters, str, as the first argument and a number, num, (num << length of string str) as the second argument.

The function should rearrange the characters of string str and construct a new string such that no two similar characters are less than num characters apart, in other words similar characters should be atleast at a distance of num characters.

The function should then finally return the new constructed string. And if it is not possible to achieve this arrangement, our function should return an empty string.

For example, if the input to the function is −

const str = 'kkllmm';

Then the output should be −

const output = 'mlmklk';

Example

The code for this will be −

 Live Demo

const str = 'kkllmm';
const placeApart = (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 len = str.length%2 ? (Math.floor(str.length/2)+1) : str.length/2;
   if(map[keys[0]] > len){
      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(placeApart(str));

Output

And the output in the console will be −

mlmklk

Updated on: 18-Mar-2021

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements