forked from realpacific/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinDeletionUniqueFrequency.kt
45 lines (39 loc) · 1.61 KB
/
MinDeletionUniqueFrequency.kt
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
package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* Minimum Deletions to Make Character Frequencies Unique
*
* A string s is called good if there are no two different characters in s that have the same frequency.
* Given a string s, return the minimum number of characters you need to delete to make s good.
*
* [Source](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/) – [Solution](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1107954/Java-Simple-Solution)
*/
@UseCommentAsDocumentation
private fun minDeletions(s: String): Int {
val countArray = IntArray(26) { 0 } // Maintain array of counts
s.forEach {
countArray[it - 'a']++
}
val alreadyTaken = mutableSetOf<Int>() // the counts that has already been seen
var deletion = 0
for (i in 0..countArray.lastIndex) {
var counts = countArray[i]
while (counts > 0 && alreadyTaken.contains(counts)) {
countArray[i]-- // Count already exists so mark it for deletion
counts = countArray[i]
deletion++
}
alreadyTaken.add(counts) // Unique count
}
return deletion
}
fun main() {
// s is already good.
minDeletions("aab") shouldBe 0
// You can delete two 'b's resulting in the good string "aaabcc".
// Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".
minDeletions(s = "aaabbbcc") shouldBe 2
// You can delete both 'c's resulting in the good string "eabaab".
minDeletions(s = "ceabaacb") shouldBe 2
}