3871. Minimum Deletions For At Most K Distinct Characters¶
3871. Minimum Deletions for At Most K Distinct Characters
Easy
You are given a string s consisting of lowercase English letters, and an integer k.
Your task is to delete some (possibly none) of the characters in the string so that the number of distinct characters in the resulting string is at most k.
Return the minimum number of deletions required to achieve this.
Example 1:
Input: s = "abc", k = 2
Output: 1
Explanation:
shas three distinct characters:'a','b'and'c', each with a frequency of 1.- Since we can have at most
k = 2distinct characters, remove all occurrences of any one character from the string. - For example, removing all occurrences of
'c'results in at mostkdistinct characters. Thus, the answer is 1.
Example 2:
Input: s = "aabb", k = 2
Output: 0
Explanation:
shas two distinct characters ('a'and'b') with frequencies of 2 and 2, respectively.- Since we can have at most
k = 2distinct characters, no deletions are required. Thus, the answer is 0.
Example 3:
Input: s = "yyyzz", k = 1
Output: 2
Explanation:
shas two distinct characters ('y'and'z') with frequencies of 3 and 2, respectively.- Since we can have at most
k = 1distinct character, remove all occurrences of any one character from the string. - Removing all
'z'results in at mostkdistinct characters. Thus, the answer is 2.
Constraints:
1 <= s.length <= 161 <= k <= 16sconsists only of lowercase English letters.
Solution¶
class Solution {
static class Pair {
char ch;
int count;
public Pair(char ch, int count) {
this.ch = ch;
this.count = count;
}
@Override
public String toString() {
return "(" + ch + " " + count + ")";
}
}
static class custom_sort implements Comparator<Pair> {
@Override
public int compare(Pair first, Pair second) {
return Integer.compare(first.count, second.count);
}
}
public int minDeletion(String s, int k) {
int n = s.length();
PriorityQueue<Pair> pq = new PriorityQueue<>(new custom_sort());
int res = 0;
int freq[] = new int[26];
for (int i = 0; i < n; i++) {
char current = s.charAt(i);
freq[current - 'a']++;
}
for (int i = 0; i < 26; i++) {
pq.offer(new Pair('a', freq[i]));
}
while (pq.size() > k) {
res += pq.poll().count;
}
return res;
}
}
Complexity Analysis¶
- Time Complexity: O(?)
- Space Complexity: O(?)
Explanation¶
[Add detailed explanation here]