Top K Frequent Elements

Heap, Sort

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.

  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

Analysis

Ref: https://leetcode.com/problems/top-k-frequent-elements/discuss/81635/3-Java-Solution-using-Array-MaxHeap-TreeMap

Max Heap

O(N + N log(N-k))

Poll Max Heap when maxheap.size() > hashmap.size() - k

Min Heap

O(N + (N-k)lg k)

Steps

  • build a counter map that maps a num to its frequency

  • build a heap/priority queue that keeps track of k most significant entries

  • iterate through the final heap and get the keys

Bucket

O(N)

For [1, 1, 1, 2, 2, 2, 3, 3, 3] and k=2, result=[1,2,3]

Solution

Max Heap

Max Heap 2 - Time: O(Nlog(N - K) + N); Space: O(N)

Min Heap - Time: O(NlogK + N); Space: O(N)

Bucket

TreeMap - Time: O(N + NlogM); Space: O(N)

Last updated

Was this helpful?