Skip to content

Commit d891f69

Browse files
committed
Add solution #358
1 parent f16cf7c commit d891f69

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,7 @@
346346
355|[Design Twitter](./solutions/0355-design-twitter.js)|Medium|
347347
356|[Line Reflection](./solutions/0356-line-reflection.js)|Medium|
348348
357|[Count Numbers with Unique Digits](./solutions/0357-count-numbers-with-unique-digits.js)|Medium|
349+
358|[Rearrange String k Distance Apart](./solutions/0358-rearrange-string-k-distance-apart.js)|Hard|
349350
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
350351
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
351352
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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

Comments
 (0)