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?- A. 1 2 3
- B. 1 2 2
- C. 2 2 3
- 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
- Problem: Does an array contain indices i < j < k with a[i] < a[j] < a[k]? An O(n), O(1) greedy keeps the smallest 'first' and the smallest…
- Problem: Can a hand of cards be split into groups of exactly w consecutive values? Greedily start groups at the smallest remaining card…
- Problem: Swap at most two digits of a number once to obtain the maximum value. Record the last position of each digit and, scanning left…
- Problem: Flower i blooms on day bloom[i]. A bouquet needs k ADJACENT bloomed flowers, each flower used once. Find the minimum day by which…
- Problem: A number is 'magical' if it is divisible by a or b. Find the n-th magical number by binary search with inclusion–exclusion…
- Problem: Find the maximum difference between successive values in the SORTED order of an array, in linear time, using buckets (pigeonhole…