Minimum Deletions to Make Character Frequencies Unique LeetCode solution in JavaScript

1
var minDeletions = function (s) {
2
let freq = new Array(26).fill(0); // Create an array to store character frequencies
3

4
for (let i = 0; i < s.length; i++) {
5
freq[s.charCodeAt(i) - "a".charCodeAt(0)]++; // Count the frequency of each character
6
}
7

8
freq.sort((a, b) => a - b); // Sort frequencies in ascending order
9

10
let del = 0; // Initialize the deletion count
11

12
for (let i = 24; i >= 0; i--) {
13
if (freq[i] === 0) {
14
break; // No more characters with this frequency
15
}
16

17
if (freq[i] >= freq[i + 1]) {
18
let prev = freq[i];
19
freq[i] = Math.max(0, freq[i + 1] - 1);
20
del += prev - freq[i]; // Update the deletion count
21
}
22
}
23

24
return del; // Return the minimum deletions required
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0