Skip to content

Commit 01347e7

Browse files
authored
Update Minimum Deletions to Make Character Frequencies Unique.java
1 parent 65f9add commit 01347e7

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed
Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
11
class Solution {
2-
public int minDeletions(String s) {
3-
int[] frequency = new int[26];
4-
for (char c : s.toCharArray()) {
5-
frequency[c - 'a']++;
6-
}
7-
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
8-
for (int freq : frequency) {
9-
if (freq > 0) {
10-
pq.add(freq);
11-
}
12-
}
13-
int numOfDeletions = 0;
14-
while (!pq.isEmpty()) {
15-
int removedFreq = pq.poll();
16-
if (!pq.isEmpty() && pq.peek() == removedFreq) {
17-
numOfDeletions++;
18-
if (removedFreq > 1) {
19-
pq.add(removedFreq - 1);
2+
public int minDeletions(String s) {
3+
int[] frequency = new int[26];
4+
for (char c : s.toCharArray()) {
5+
frequency[c - 'a']++;
6+
}
7+
Arrays.sort(frequency);
8+
int numOfDeletions = 0;
9+
int expectedFrequency = frequency[25];
10+
for (int i = 25; i >= 0; i--) {
11+
if (frequency[i] == 0) {
12+
break;
13+
}
14+
if (frequency[i] > expectedFrequency) {
15+
numOfDeletions += frequency[i] - expectedFrequency;
16+
} else {
17+
expectedFrequency = frequency[i];
18+
}
19+
if (expectedFrequency > 0) {
20+
expectedFrequency--;
21+
}
2022
}
21-
}
23+
return numOfDeletions;
2224
}
23-
return numOfDeletions;
24-
}
2525
}

0 commit comments

Comments
 (0)