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?- A. 3 2
- B. 2 2
- C. 3 3
- 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
- Problem: An array of n + 1 integers holds values 1..n with exactly one value repeated (possibly several times). Find it in O(1) extra…
- Problem: Find all values appearing more than ⌊n/3⌋ times with the extended Boyer–Moore vote (two candidates), then verify. python def…
- Find the bug: Boyer–Moore majority vote is used WITHOUT the verification pass on an array that may have no majority. python def…
- A 'shuffle' swaps each position i with a position chosen uniformly from the WHOLE array (0..n−1), for i = 0..n−1. Why is this not a…
- What is the time complexity of this loop? python for i in range(1, n + 1): j = i while j <= n: work() # O(1) j += i
- Problem: Maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best = a[0] for x in…