Data Structures & AlgorithmsModerateAmazon · Microsoft 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(["sql", "api", "node", "api", "sql", "go", "node", "rust", "go"], 3))What is printed?- A. ['api', 'sql', 'node']
- B. ['api', 'go', 'node']
- C. ['sql', 'api', 'node']
- D. ['api', 'go', 'sql']
Correct answer: B. ['api', 'go', 'node']
api, sql, node and go each appear twice and rust once. Sorting by (−count, word) puts the tied words in alphabetical order: api, go, node, sql, so the top 3 are api, go, node. Taking the first-seen order instead gives sql, api, node.
More Coding Interview Problems questions
- Design a set supporting insert, delete and getRandom (uniform) all in O(1) average time. Which design works?
- Problem: Rotate a linked list to the right by k places. python class N: def init(s, v, nx=None): s.v, s.nx = v, nx def rotate(h, k): n, t…
- Problem: Partition a linked list so that all nodes with values < x come before nodes ≥ x, preserving relative order within each part…
- List A has a nodes before it joins a shared tail of c nodes; list B has b nodes before the same tail, with a ≠ b. Pointer p walks A and…
- Problem: Move the coins of a binary tree so every node has exactly one coin; a move passes one coin along one edge. Count the minimum…
- Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree. python class T: def init(s, v): s.v, s.l, s.r = v, None…