-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimum deletions to make character frequencies unique
49 lines (38 loc) · 1.31 KB
/
Minimum deletions to make character frequencies unique
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Minimum deletions to make character frequencies unique - medium - 30/08/2023
public int minDeletions(String s) {
int[] count = new int[26];
for(char c: s.toCharArray()){
count[c-'a']++;
}
Map<Integer, Integer> freqsMap = new HashMap<>();
for (int n: count) if (n != 0) freqsMap.put(n, freqsMap.getOrDefault(n,0) + 1);
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int key: freqsMap.keySet()) pq.add(key);
int deletions = 0;
while (!pq.isEmpty()) {
int val = pq.poll(), freq = freqsMap.get(val);
deletions += freq - 1;
if (freq > 1 && val > 1) {
if (!freqsMap.containsKey(val-1)) pq.add(val-1);
freqsMap.put(val-1, freqsMap.getOrDefault(val-1,0) + freq-1);
}
}
return deletions;
}
// Approach 2 - optimized
ublic int minDeletions(String s) {
int deletion=0;
int []freq=new int[26];
for(char c : s.toCharArray()){
freq[c-'a']++;
}
HashSet<Integer> uniqueelement = new HashSet<>();
for(int count:freq){
while(count>0 && uniqueelement.contains(count)){
deletion++;
count--;
}
uniqueelement.add(count);
}
return deletion;
}