Python interview question: top k frequent elements

MediumHash maps

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

Solve it free

Checked against hidden tests, right in your browser. No sign-up needed.

Skills it tests

More interview questions

All questions