LeetCode 1647: Minimum Deletions to Make Character Frequencies Unique Solution
Master LeetCode problem 1647 (Minimum Deletions to Make Character Frequencies Unique), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1647. Minimum Deletions to Make Character Frequencies Unique
Problem Explanation
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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1647 (Minimum Deletions to Make Character Frequencies Unique)?
This page provides optimized solutions for LeetCode problem 1647 (Minimum Deletions to Make Character Frequencies Unique) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1647 (Minimum Deletions to Make Character Frequencies Unique)?
The time complexity for LeetCode 1647 (Minimum Deletions to Make Character Frequencies Unique) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1647 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1647 in Java, C++, or Python.