Created
May 13, 2021 07:33
-
-
Save shivshankar3578/c9bfbe5668d09d21c5cf95b1014f7c75 to your computer and use it in GitHub Desktop.
rearrange characters in a string such that no two adjacent are same
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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