Data Structures & AlgorithmsHardProduct company OA

Problem: Delete the fewest characters so that no two distinct letters have the same (non-zero) frequency.

Problem: Delete the fewest characters so that no two distinct letters have the same (non-zero) frequency.
from collections import Counter
def min_del(s):
    used, dels = set(), 0
    for f in sorted(Counter(s).values(), reverse=True):
        while f and f in used:
            f -= 1; dels += 1
        used.add(f)
    return dels
print(min_del("mississippi"), min_del("kkkllloo"), min_del("abcabc"))
What is printed?
  1. A. 1 2 3
  2. B. 1 2 2
  3. C. 2 2 3
  4. D. 1 1 3

Correct answer: A. 1 2 3

Process frequencies from largest down and lower each one until it is unused (0 is always allowed – the letter disappears). "mississippi": 4, 4, 2, 1 → 4, 3, 2, 1 → 1 deletion. "kkkllloo": 3, 3, 2 → 3, 2, and then 2 must drop to 1 → 2 deletions. "abcabc": 2, 2, 2 → 2, 1, 0 → 3. O(n + k²) worst case for k distinct letters, k ≤ 26.

More Coding Interview Problems questions

Exams that ask this topic