You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
varreorganizeString=function(s){constmap=newMap();// 1. building maps.split('').forEach((letter)=>{map.set(letter,map.get(letter)+1||1);})// 1. sorting the map based on the occurances in descending order.constsortedMap=newMap([...map.entries()].sort((a,b)=>b[1]-a[1]));// 2. getting the first value of sorted map and checking if greater than half of string lengthif(sortedMap.values().next().value>(s.length+1)/2)return"";constres=[];letindex=0;for(let[key,value]ofsortedMap){while(value--){// 5. if it reaches the end of string, start filling from odd position.if(index>=s.length)index=1;// 4. adding elements at even position.res[index]=keyindex+=2}}// converting array back to stringreturnres.join('');};