
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Format 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
Advertisements