Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Remove the fewest DISTINCT values so that at least half of the array's elements are removed (greedy on frequencies).

Problem: Remove the fewest DISTINCT values so that at least half of the array's elements are removed (greedy on frequencies).
from collections import Counter
def half(a):
    removed = cnt = 0
    for f in sorted(Counter(a).values(), reverse=True):
        removed += f; cnt += 1
        if removed * 2 >= len(a): return cnt
print(half([3, 3, 3, 3, 5, 5, 5, 2, 2, 7, 1, 9]))
What is printed?
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: C. 2

n = 12, so at least 6 elements must go. Frequencies 4 (3s), 3 (5s), 2, 1, 1, 1: removing 3s and 5s takes out 7 ≥ 6 with just 2 distinct values. Removing the most frequent values first is optimal.

More Coding Interview Problems questions

Exams that ask this topic