Minimum Deletions to Make Character Frequencies Unique - Problem

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.

The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1.

Input & Output

Example 1 — Basic Case
$ Input: s = "aab"
Output: 0
💡 Note: Character frequencies: a=2, b=1. All frequencies are unique, so no deletions needed.
Example 2 — Need Deletions
$ Input: s = "aaabbbcc"
Output: 2
💡 Note: Character frequencies: a=3, b=3, c=2. We have duplicate frequency 3. Reduce one character's frequency: 3→1, requiring 2 deletions.
Example 3 — Complex Case
$ Input: s = "ceabaacb"
Output: 2
💡 Note: Character frequencies: a=3, b=2, c=2, e=1. Two characters have frequency 2. Reduce one to frequency 1, but that conflicts with e=1, so reduce to 0. Total: 2 deletions.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters only

Visualization

Tap to expand
Minimum Deletions for Unique Frequencies INPUT String s = "aab" 'a' 'a' 'b' Character Frequencies: 'a': 2 'b': 1 Sorted Frequencies: 2 1 [2, 1] - descending ALGORITHM STEPS 1 Count Frequencies Map each char to count 2 Sort Descending Sort freqs: [2, 1] 3 Check Uniqueness Compare adjacent pairs 4 Count Deletions Delete if duplicate freq Frequency Check freq[0] = 2 freq[1] = 1 2 != 1 -- OK! All unique - no deletions FINAL RESULT Original String: a a b Result String (unchanged): a a b Output: 0 String is already "good" No deletions needed! Key Insight: Greedy approach: Sort frequencies descending, then iterate through them. If current frequency equals or exceeds previous, reduce it to (previous - 1) and count deletions. This ensures all frequencies become unique with minimum deletions. Time: O(n), Space: O(26) = O(1). TutorialsPoint - Minimum Deletions to Make Character Frequencies Unique | Greedy with Sorting
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
89.5K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen