Minimum Deletions to Make Character Frequencies Unique, explained

To find the minimum deletions that make character frequencies unique, count each letter, sort the counts from largest to smallest, and lower each count to at most one less than the count you kept before it, stopping at zero. The sum of the reductions is the answer, in O(n) time for a fixed alphabet.

By Published 7 min read

The task, reworded

You get a string of lowercase letters. Call a string balanced in an odd way if every letter that appears in it appears a different number of times from every other letter. You may delete characters from anywhere. Return the smallest number of deletions that leaves such a string. Only the counts matter, so the positions of the letters never come into it.

Strings made up for this page, with their letter counts
StringCountsFewest deletionsOne way to get there
aabbbccb:3, a:2, c:21Drop one c, leaving counts 3, 2, 1.
zzzzyyyxxz:4, y:3, x:20Already distinct.
ppqqrr2, 2, 23Keep 2 and 1, delete the third letter completely: 0 + 1 + 2.
kkkkllll4, 41Lower one letter to 3.
mmnnoopq2, 2, 2, 1, 15Kept counts 2, 1, 0, 0, 0.
Strings made up for this page, with their letter counts. Scroll sideways on a small screen.

The third row is the one to discuss early. Removing a letter entirely is allowed, and once a letter has zero copies it no longer clashes with anything. Ask the interviewer whether the string can contain uppercase letters or digits, because that decides whether a 26-slot array or a hash map holds the counts.

What the interviewer is looking for

The problem rewards turning a string question into a question about a small list of numbers. After that, it is a greedy argument about which counts to lower. Candidates who start editing the string itself, or simulating deletions character by character, usually run out of time. Saying early that only the frequency list matters is a strong signal.

Exhaustive search over kept counts

A letter with count c can end with any count from 0 to c. Try every combination, keep the ones where the nonzero values are all different, and take the one that deletes least. With k distinct letters this is the product of (c + 1) over all letters, which is exponential in k. It is only good for tiny inputs and for checking a faster answer.

from collections import Counter
from itertools import product

def fewest_deletions_search(text):
    counts = list(Counter(text).values())
    best = len(text)
    for kept in product(*(range(c + 1) for c in counts)):
        present = [x for x in kept if x > 0]
        if len(present) == len(set(present)):
            best = min(best, len(text) - sum(kept))
    return best
Brute force over every choice of kept counts.

Greedy: sort the counts and cap each one

Sort the counts from largest to smallest. The largest letter can keep everything. Each next letter can keep at most its own count, and at most one less than what the previous letter kept, so the kept values strictly fall. Once the cap reaches zero, every remaining letter is deleted completely. Add up the differences between the original and kept counts.

Why is that the best possible? In any valid final string, list the kept counts in decreasing order. You can always pair the biggest kept count with the biggest original count, the next with the next, and so on, without deleting more, because swapping two letters' targets so the larger original gets the larger target never makes a target exceed its count. Under that pairing, the i-th letter's kept value can be no more than its own count and no more than the previous kept value minus one. The greedy takes exactly that maximum at every step, so it keeps the most characters and deletes the fewest.

from collections import Counter

def fewest_deletions(text):
    deletions = 0
    cap = len(text)
    for count in sorted(Counter(text).values(), reverse=True):
        keep = min(count, cap)
        deletions += count - keep
        cap = max(keep - 1, 0)
    return deletions
Python: sort the frequencies, then walk them with a falling cap.
function fewestDeletions(text) {
  const counts = new Array(26).fill(0);
  for (const ch of text) counts[ch.charCodeAt(0) - 97]++;
  counts.sort((a, b) => b - a);
  let deletions = 0;
  let cap = text.length;
  for (const count of counts) {
    if (count === 0) break;
    const keep = Math.min(count, cap);
    deletions += count - keep;
    cap = Math.max(keep - 1, 0);
  }
  return deletions;
}
JavaScript: a 26-slot array for lowercase input, sorted in descending order.

Trace mmnnoopq. Sorted counts are 2, 2, 2, 1, 1. The first keeps 2 and the cap becomes 1. The second keeps 1 and deletes 1, cap 0. The third keeps 0 and deletes 2. The two ones each delete 1. Total: 0 + 1 + 2 + 1 + 1 = 5.

The set version many people write first

Without sorting, you can keep a set of counts already taken. For each letter, lower its count one step at a time while the value is taken and above zero, counting each step as a deletion, then record the value. Each step deletes a real character, so the total work across all loops is at most the string length.

from collections import Counter

def fewest_deletions_with_set(text):
    taken = set()
    deletions = 0
    for count in Counter(text).values():
        while count > 0 and count in taken:
            count -= 1
            deletions += 1
        taken.add(count)
    return deletions
Set-based greedy, no sorting needed.

Complexity summary

n characters, k distinct letters
VersionTimeSpace
Every combination of kept countsProduct of (count + 1) over lettersO(k)
Sorted counts with a capO(n + k log k)O(k)
Set of taken countsO(n + k)O(k)
n characters, k distinct letters. Scroll sideways on a small screen.

With a lowercase alphabet, k is at most 26, so both greedy versions are effectively linear in the string length. Counting the characters is the only part that grows with n.

Inputs to try

  • An empty string: zero deletions.
  • One letter repeated: zero deletions, since a single count cannot clash.
  • Every letter different, such as abcde: each count is 1, so keep one letter and delete the other four.
  • Many letters sharing a large count: the kept values form a staircase down from that count and may reach zero.
  • A count already lower than the cap, like 9, 9, 2: the third letter keeps 2 untouched because the cap is 7.

Where answers go wrong

  • Insisting that zero counts be unique too. Fully deleted letters are gone and cannot clash.
  • Returning the number of distinct letters minus the number of distinct counts. For ppqqrr that gives 2, but the real answer is 3.
  • Letting the cap go negative after a zero, then subtracting a negative keep.
  • Sorting ascending and capping upward, which lowers small counts that never needed to move.
  • Using character codes minus 97 on input that contains capitals. Ask first, or use a map.

Putting it into words

Fictional example

A candidate's spoken summary
Candidate
Positions do not matter, only how many times each letter appears, so I turn the string into a list of counts.
Candidate
I sort those descending. Each letter keeps the smaller of its count and one less than the previous letter kept, and never below zero.
Candidate
Counting is linear, sorting at most 26 numbers is constant, so the whole thing is O(n) with O(1) extra space for lowercase input.

Queue Reconstruction by Height uses the same habit of handling the biggest values first, and Break a Palindrome is another string problem where a short greedy rule needs a careful edge case. The algorithm interview questions guide groups these patterns.

Natively as a practice partner

While you study, Natively can capture a screenshot of a counting problem like this one, read the statement and offer an approach with code, so you can compare it with the solution you wrote yourself. It also keeps a transcript of a mock interview on your computer, which shows whether you explained why fully deleted letters stop clashing. Learn more about an AI interview assistant for desktop.

Questions people ask

How do you find the minimum deletions to make character frequencies unique?

Count each character, sort the counts in descending order, and let each one keep the smaller of its count and one less than the previous kept count, never going below zero. Add up what was removed.

Do letters with zero occurrences have to be unique?

No. A letter that is deleted completely is no longer in the string, so any number of letters can end at zero.

What is the time complexity?

Counting is O(n). Sorting the counts is O(k log k) for k distinct letters, which is at most 26 for lowercase input, so the total is O(n) with O(1) extra space.

Is there a solution without sorting?

Yes. Keep a set of counts already used and lower each new count one step at a time until it is free or zero. Every step deletes a real character, so the total work stays linear.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP