Top pin categories

hashing

Top pin categories

Pinterest Python Interview Question

Pinterest's home feed shows each user the categories they save most often.

Write a function top_categories(categories, k) that takes a list with the category of each saved pin and returns the k most common categories, most common first. Break ties alphabetically. If there are fewer than k different categories, return all of them.

Asked of

  • Data Engineer
  • Data Scientist
  • Analytics Engineer
  • ML Engineer
  • AI Engineer

Example 1

Input

top_categories(["food", "diy", "food", "travel", "diy", "food"], 2)

Output

["food", "diy"]

Example 2

Input

top_categories(["art"], 1)

Output

["art"]

Explanation

In the first example, food was saved three times and diy twice, so with 2 slots the answer is food, then diy. Travel was saved once, so it does not make the top two.

Submit also runs 3 hidden test cases that check edge cases.