|
| 1 | +/** |
| 2 | + * 358. Rearrange String k Distance Apart |
| 3 | + * https://leetcode.com/problems/rearrange-string-k-distance-apart/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a string s and an integer k, rearrange s such that the same characters are at least |
| 7 | + * distance k from each other. If it is not possible to rearrange the string, return an empty |
| 8 | + * string "". |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * @param {string} s |
| 13 | + * @param {number} k |
| 14 | + * @return {string} |
| 15 | + */ |
| 16 | +var rearrangeString = function(s, k) { |
| 17 | + if (k <= 1) return s; |
| 18 | + |
| 19 | + const charCount = new Array(26).fill(0); |
| 20 | + for (const char of s) { |
| 21 | + charCount[char.charCodeAt(0) - 97]++; |
| 22 | + } |
| 23 | + |
| 24 | + const maxHeap = []; |
| 25 | + for (let i = 0; i < 26; i++) { |
| 26 | + if (charCount[i] > 0) { |
| 27 | + maxHeap.push([charCount[i], String.fromCharCode(i + 97)]); |
| 28 | + } |
| 29 | + } |
| 30 | + maxHeap.sort((a, b) => b[0] - a[0]); |
| 31 | + |
| 32 | + const maxFreq = maxHeap[0] ? maxHeap[0][0] : 0; |
| 33 | + if (maxFreq > Math.ceil(s.length / k)) return ''; |
| 34 | + |
| 35 | + const result = new Array(s.length).fill(''); |
| 36 | + let index = 0; |
| 37 | + |
| 38 | + while (maxHeap.length) { |
| 39 | + const temp = []; |
| 40 | + for (let i = 0; i < k && maxHeap.length; i++) { |
| 41 | + const [count, char] = maxHeap.shift(); |
| 42 | + while (index < s.length && result[index] !== '') { |
| 43 | + index++; |
| 44 | + } |
| 45 | + if (index >= s.length) index = 0; |
| 46 | + result[index] = char; |
| 47 | + index++; |
| 48 | + if (count > 1) temp.push([count - 1, char]); |
| 49 | + } |
| 50 | + |
| 51 | + temp.sort((a, b) => b[0] - a[0]); |
| 52 | + maxHeap.push(...temp); |
| 53 | + maxHeap.sort((a, b) => b[0] - a[0]); |
| 54 | + } |
| 55 | + |
| 56 | + for (let i = 0; i <= s.length - k; i++) { |
| 57 | + const seen = new Set(); |
| 58 | + for (let j = i; j < i + k; j++) { |
| 59 | + if (seen.has(result[j])) return ''; |
| 60 | + seen.add(result[j]); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return result.join(''); |
| 65 | +}; |
0 commit comments