Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the k most frequent words, ties broken alphabetically.
Problem: Return the k most frequent words, ties broken alphabetically.
from collections import Counter
def topk(words, k):
c = Counter(words)
return sorted(c, key=lambda w: (-c[w], w))[:k]
print(topk(["the", "day", "is", "sunny", "the", "the", "sunny", "is", "is"], 4))What is printed?- A. ['the', 'is', 'sunny', 'day']
- B. ['is', 'the', 'day', 'sunny']
- C. ['the', 'is', 'sunny']
- D. ['is', 'the', 'sunny', 'day']
Correct answer: D. ['is', 'the', 'sunny', 'day']
Sort by (−count, word): 'is' and 'the' both appear 3 times, so alphabetical order puts 'is' first; then 'sunny' (2) and 'day' (1). Sorting by count alone keeps insertion order for ties ('the' first). O(m log m) for m distinct words; a size-k heap gives O(m log k).
More Coding Interview Problems questions
- Problem: Check whether two strings are isomorphic (characters map one-to-one consistently). python def iso(s, t): return len(set(s)) ==…
- Problem: Find the minimum number of swaps to sort an array of distinct values. python def minswaps(a): order = sorted(range(len(a))…
- Problem: Count the distinct values taken by the bitwise OR of all contiguous subarrays. python def distinctor(a): res, cur = set(), set()…
- Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit. python def maxxor(a): ans = mask = 0…
- Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range. python…
- Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7. java static long ways3(int n) { long MOD =…