Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Delete the fewest characters so that no two letters have the same (nonzero) frequency.

Problem: Delete the fewest characters so that no two letters have the same (nonzero) 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("aabbccddd"), min_del("ceabaacb"))
What is printed?
  1. A. 3 2
  2. B. 2 2
  3. C. 3 3
  4. D. 4 2

Correct answer: A. 3 2

Frequencies 3, 2, 2, 2 must become distinct: 3, 2, 1, 0 → 0 + 0 + 1 + 2 = 3 deletions. For 'ceabaacb': a = 3, b = 2, c = 2, e = 1 → 3, 2, 1, 0 → 2 deletions (one c and the e). Reaching 0 means the letter disappears, which is allowed.

More Coding Interview Problems questions

Exams that ask this topic