Skip to content

Instantly share code, notes, and snippets.

@shivshankar3578
Created May 13, 2021 07:33
Show Gist options
  • Select an option

  • Save shivshankar3578/c9bfbe5668d09d21c5cf95b1014f7c75 to your computer and use it in GitHub Desktop.

Select an option

Save shivshankar3578/c9bfbe5668d09d21c5cf95b1014f7c75 to your computer and use it in GitHub Desktop.
rearrange characters in a string such that no two adjacent are same
Array.prototype.swap = function (idx1, idx2) {
const temp = this[idx1];
this[idx1] = this[idx2];
this[idx2] = temp;
}
function rearrange(str) {
const weightMap = str.split("").reduce((acc, curr) => {
acc[curr] ? acc[curr] += 1 : acc[curr] = 1
return acc
}, {})
console.log(weightMap)
const sortedWeight = Object.keys(weightMap).sort((curr, next) => {
return weightMap[next] - weightMap[curr]
})
console.log(sortedWeight)
if (weightMap[sortedWeight[0]] > str.length / 2) return console.log("Impossible to rearrange")
const res = []
while (res.length < str.length) {
const w = sortedWeight[0];
res.push(w);
weightMap[w] -= 1
let swapped = false;
for (let index = 1; index < sortedWeight.length; index++) {
const w1 = sortedWeight[index];
if (weightMap[w1] < weightMap[w]) {
sortedWeight.swap(0, index - 1);
swapped = true
break;
}
}
if (!swapped) sortedWeight.push(sortedWeight.shift())
}
console.log(res.join(""))
}
rearrange("aaaspppp")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment