Problem 487716 · medium · Level 04 Non-Linear Data Structures

Most-Requested Songs

heap · hash map · Counter

A late-night radio show logs every listener request in the list nums, either as catalogue numbers or as song titles. Write top_k_frequent(nums, k) that returns the k songs requested most often, so the presenter knows what to play. No two songs tie at the cut-off, so the answer is unique; return the songs in any order.

Examples

Input:  nums = [7, 3, 7, 5, 3, 7, 9], k = 2
Output: [7, 3]
Explanation: 7 was requested three times and 3 twice.
Input:  nums = [4], k = 1
Output: [4]
Input:  nums = ["a", "b", "a", "c", "b", "a"], k = 2
Output: ["a", "b"]

Constraints

  • 1 <= len(nums) <= 10**4
  • 1 <= k <= number of distinct elements
  • Elements are all ints or all strings.

Goals

  • Count occurrences with a dictionary or collections.Counter
  • Push tuples onto a heap so that the first element decides the order
  • Select the k best items from n in O(n log k) with a size-limited heap
Starting Python…