#1647

Minimum Deletions to Make Character Frequencies Unique

Medium
Hash TableStringGreedySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages a frequency count of characters and a greedy approach to ensure frequencies are unique by decrementing duplicates. This is efficient and avoids unnecessary computations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each character in the string.
  2. 2Step 2: Store these frequencies in a list and sort it in descending order.
  3. 3Step 3: Iterate through the sorted frequencies and ensure each frequency is unique by decrementing duplicates and counting the deletions needed.
  4. 4Step 4: Return the total number of deletions.
solution.py15 lines
1# Full working Python code
2from collections import Counter
3
4def min_deletions_optimal(s):
5    freq = Counter(s)
6    freq_values = sorted(freq.values(), reverse=True)
7    deletions = 0
8    seen = set()
9    for f in freq_values:
10        while f in seen and f > 0:
11            f -= 1
12            deletions += 1
13        seen.add(f)
14    return deletions
15

Complexity note: The time complexity is O(n log n) due to sorting the frequency list, while the space complexity is O(n) for storing the frequency counts.

  • 1Character frequencies must be unique to make the string good.
  • 2Using a greedy approach allows us to minimize deletions efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.