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?- A. 1
- B. 3
- C. 2
- 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
- Problem: Find a target's index in a rotated sorted array of distinct values in O(log n). python def search(a, t): lo, hi = 0, len(a) - 1…
- Problem: You take trains in order; train i covers dist[i] km at a common integer speed, and every train except the last departs only at an…
- Problem: Koko eats from one pile per hour at speed k bananas/hour (if a pile has fewer, she finishes it and waits). Find the minimum k to…
- Problem: Length of the longest common subsequence of THREE strings (3-D DP). python def lcs3(a, b, c): dp = [[[0] (len(c) + 1) for in…
- Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS. python from functools…
- Problem: Smash stones pairwise (x ≤ y leaves y − x) until at most one remains; minimise the final weight. Equivalent to splitting into two…