Magicsheet logo

Minimum Deletions to Make Character Frequencies Unique

Medium
100%
Updated 6/1/2025

Minimum Deletions to Make Character Frequencies Unique

1. What is this problem about?

The Minimum Deletions to Make Character Frequencies Unique problem asks you to modify a string so that no two different characters have the same frequency. For example, in the string "aabb", 'a' and 'b' both have frequency 2, which is not allowed. You can delete characters to change their frequencies. The goal is to find the minimum number of deletions needed to make all non-zero frequencies unique.

2. Why is this asked in interviews?

This "Medium" problem is a favorite at Microsoft and Amazon because it tests Greedy logic and the use of Set data structures. The Minimum Deletions to Make Character Frequencies Unique interview question assesses your ability to resolve conflicts (duplicate frequencies) by making the smallest possible changes. It's a great test of how you handle frequency counts and uniqueness constraints.

3. Algorithmic pattern used

The algorithmic pattern is Greedy with a Hash Table (or frequency array) and a Set.

  1. Count the frequency of each character.
  2. Store the seen frequencies in a Set.
  3. For each character's frequency, if it's already in the Set, decrement it (counting each decrement as a deletion) until it becomes unique or reaches zero.
  4. Add the resulting unique frequency to the Set. This "Hash Table, Sorting, String, Greedy interview pattern" ensures that you only delete as much as necessary to reach the next available "slot" in the frequency space.

4. Example explanation

String: "aaabbbcc". Frequencies: a: 3, b: 3, c: 2.

  1. Seen set: {}.
  2. Frequency 3 ('a'): Add to set. Seen: {3}.
  3. Frequency 3 ('b'): Already in set! Decrement to 2. Is 2 in set? No (not yet). Add 2 to set. Deletions = 1. Seen: {3, 2}.
  4. Frequency 2 ('c'): Already in set! Decrement to 1. Is 1 in set? No. Add 1 to set. Deletions = 1 + 1 = 2. Seen: {3, 2, 1}. Total deletions = 2.

5. Common mistakes candidates make

In the Minimum Deletions to Make Character Frequencies Unique coding problem, some candidates try to sort characters first, which is unnecessary. Others might forget that a frequency can be reduced all the way to 0 (effectively removing the character), and 0 does not need to be unique. A common error is also overcomplicating the "search" for a new frequency; a simple while loop with a Set check is both efficient and correct.

6. Interview preparation tip

When you need to make values unique with minimal decrements, always use a Set to keep track of "taken" values and a greedy approach to move to the next available smaller value. This "Uniqueness interview pattern" is a recurring theme in many optimization problems. Practice managing counts and sets together.

Similar Questions