Top K frequent elements
Problem Statement
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
1. Hashing + Sorting
Metric | Complexity |
---|---|
Time | \( O(n \cdot logn ) \) β¦ Sorting |
Space | \( O(n) \) β¦ Frequency map |
2. Hashing + Heap
As βTop Kβ frequent elements asked, we should think of heap
The heap should be such that the highest frequency elements placed first and then the lower frequncey ones. In other words, a max-heap with the comparison basis as frequency of the number in input array
Assuming there are β\(m\)β unique elements, which is at worst β\(n\)β.
Also, β\(k\)β will be β\(m\)β at most
Time:
- \( O(n) \) to traverse array elements and construct frequency map
- \( m \) insertions into max-heap is \( O(m \cdot logm) \) , which will be \( O(n \cdot logn) \) at worst
- \( k \) elements popped from max-heap takes \( O(k \cdot logm) \) , which will be \( O(n \cdot logn) \) at worst
Space: Β \( n \) elements at worst in frequency map and heap and answer i.e. \( O(2n) \)
Metric | Complexity |
---|---|
Time | \( O(n + k \cdot logm ) \) Β which at worst is Β \( O(n \cdot logn ) \) |
Space | \( O(n) \) |
C++ code
3. Hashing + Buckets
The frequency count of any number in the input can range between: \( 0 \text{ to } n \)
We can create \( n \) buckets where each bucket represents elements having that count. The index of the bucket will be the frequency count of itβs elements
Example:
Time:
- \( O(n) \) to traverse array elements and construct frequency map
- \( m \) insertions into respective buckets is \( O(m) \) , which will be \( O(n) \) at worst
- Traverse buckets and append elements into answer: would be \( O(n) \) amortized
Space: Β \( n \) elements at worst in frequency map and \( n \) buckets and combined elements of all buckets would be \( n \) at worst
Metric | Complexity |
---|---|
Time | \( O(n) \) |
Space | \( O(n) \) |