Problems › Hashing

Top K Frequent Elements

Difficulty: Medium · Topic: Hashing

Given an integer array nums and an integer k, return the k most frequent elements. The answer is unique for the given inputs; return them in any order.

Examples

top_k_frequent([1,1,1,2,2,3], 2)
→ [1,2]

1 appears 3×, 2 appears 2×.

top_k_frequent([1], 1)
→ [1]

Target complexity: time O(n log n), space O(n)

Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.

Learn the idea first: the lesson for this problem.

More Hashing problems