LeetCode 1647: Minimum Deletions to Make Character Frequencies Unique
Problem Description
Explanation
To solve this problem, we can iterate through the characters of the input string s
and count the frequency of each character. We can then keep track of the frequencies we have seen so far in a set. If we encounter a frequency that is already in the set, we need to increment our deletion count. In the end, the total number of deletions needed will be the sum of all duplicate frequencies encountered.
Algorithm:
- Initialize a map to store the frequency of each character in the string.
- Initialize a set to keep track of frequencies we have seen.
- Iterate through the characters in the string, update the frequency map, and check for duplicates in the set.
- If a frequency is already in the set, increment the deletion count.
- Add the frequency to the set.
- Return the total deletion count.
Time Complexity: O(n), where n is the length of the input string s
.
Space Complexity: O(n), where n is the length of the input string s
.
Solutions
class Solution {
public int minDeletions(String s) {
int[] freq = new int[26];
Set<Integer> seen = new HashSet<>();
int deletions = 0;
for (char c : s.toCharArray()) {
freq[c - 'a']++;
}
for (int f : freq) {
while (f > 0 && !seen.add(f)) {
f--;
deletions++;
}
}
return deletions;
}
}
Loading editor...