Skip to content

Commit 9e12abe

Browse files
Update 1647-minimum-deletions-to-make-character-frequencies-unique.java
1 parent bd4f66a commit 9e12abe

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,20 @@
11
class Solution {
22
public int minDeletions(String s) {
3-
int[] chars = new int[26];
4-
for (char c : s.toCharArray()) {
5-
chars[c - 'a']++;
3+
// This Map stores the frequency of characters in String s.
4+
HashMap<Character, Integer> map = new HashMap<>();
5+
for(char c: s.toCharArray()){
6+
map.put(c, map.getOrDefault(c, 0) + 1);
67
}
7-
8-
int[] arr = Arrays.stream(chars).boxed()
9-
.sorted(Collections.reverseOrder())
10-
.mapToInt(Integer::intValue)
11-
.toArray();
12-
int frequency = arr[0];
8+
// This set stores the frequency of Characters that we encounter
9+
HashSet<Integer> set = new HashSet<>();
1310
int res = 0;
14-
for (int i : arr) {
15-
if (i > frequency) {
16-
if (frequency > 0)
17-
res += (i - frequency);
18-
else
19-
res += i;
11+
for (char c: map.keySet()){
12+
while (map.get(c) > 0 && set.contains(map.get(c))){
13+
map.put(c, map.get(c)-1);
14+
res++;
2015
}
21-
frequency = Math.min(frequency - 1, i - 1);
16+
set.add(map.get(c));
2217
}
2318
return res;
2419
}
25-
}
20+
}

0 commit comments

Comments
 (0)