Python interview question: top k frequent elements
Problem
For the app’s “Frequently ordered” block, return the k most frequent ids in product_ids (one id per order line), most frequent first. On a tie, the smaller id comes first. If there are fewer than k distinct products, return them all.
def top_k_products(product_ids: list[int], k: int) -> list[int]:
Example
product_ids = [101, 205, 101, 333, 205, 101, 412], k = 2 → [101, 205]product_ids = [8, 3, 8, 3, 5], k = 1 → [3]8 and 3 both occur twice; the smaller id wins
Solve it free
Checked against hidden tests, right in your browser. No sign-up needed.