Top K Frequent Elements
Medium · Heap & Counting · Array · Hash Table · Heap · Bucket Sort
Problem
Given an integer array nums and an integer k, return the k most frequent elements, in any order.
Examples
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
1 appears three times, 2 twice.
Input: nums = [1], k = 1 Output: [1]
Constraints
- 1 <= len(nums) <= 10^5
- k is between 1 and the number of distinct values
- The answer is unique
Approaches
- Counter, then sort by count — time O(n log n), space O(n)
Follow-up
Your algorithm should run faster than O(n log n), where n is the array's length.
Related problems
Start free on Cariara · Coding problems · System design studio