For frequencies to be unique, no two characters can have the same count. When we encounter a frequency that already exists, we must delete characters until we reach an unused frequency (or zero). A hash set tracks which frequencies are already taken. For each character's frequency, we decrement it until we find an available slot, counting each decrement as a deletion.
Where is the length of the string and is the total number of unique frequncies possible.
Using a max-heap, we process frequencies from largest to smallest. When the top two frequencies are equal, we have a conflict. We resolve it by decrementing one of them and pushing the reduced value back (if still positive). This greedy approach ensures we minimize deletions by keeping larger frequencies intact when possible.
class Solution:
def minDeletions(self, s: str) -> int:
freq = Counter(s)
maxHeap = [-f for f in freq.values()]
heapq.heapify(maxHeap)
res = 0
while len(maxHeap) > 1:
top = -heapq.heappop(maxHeap)
if top == -maxHeap[0]:
if top - 1 > 0:
heapq.heappush(maxHeap, -(top - 1))
res += 1
return resWhere is the length of the string and is the total number of unique frequncies possible.
By sorting frequencies in descending order, we process them from highest to lowest. We track the maximum allowed frequency for the next character. If a frequency exceeds this limit, we delete down to the limit. After each character, the next allowed frequency decreases by one (minimum 0). This ensures all final frequencies are distinct.
maxAllowedFreq to the highest frequency.maxAllowedFreq, add the difference to deletions.maxAllowedFreq to max(0, current_frequency - 1).class Solution:
def minDeletions(self, s: str) -> int:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
count.sort(reverse=True)
res = 0
maxAllowedFreq = count[0]
for freq in count:
if freq > maxAllowedFreq:
res += freq - maxAllowedFreq
freq = maxAllowedFreq
maxAllowedFreq = max(0, freq - 1)
return resWhere is the length of the string and is the total number of unique frequncies possible.
When a frequency is decremented to zero, adding it to the used frequency set prevents other characters from also being reduced to zero. Multiple characters can validly have frequency zero (meaning they are completely deleted), so zero should either not be added or handled specially.
Some implementations only check if a frequency is taken and decrement once. The correct approach requires a while loop that continues decrementing until finding an unused frequency or reaching zero. A single decrement may land on another taken frequency.
The problem asks for minimum deletions to make frequencies unique, not to make characters unique. Confusing the two leads to counting unique characters or deleting entire character types rather than reducing specific frequency counts.