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

Top K Frequent Elements

heap · hash map · Counter

Given a list nums and an integer k, return the k most frequent elements. The answer is guaranteed to be unique (no ties at the boundary), and you may return the elements in any order.

Examples

Input:  nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]
Input:  nums = [1], k = 1
Output: [1]
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…