LEARNING JOURNAL

I created this learning journal to practice writting and to help me learn by writting everything down. Source code here

2/17/2024

Top K Frequent Elements - Binary Heap

THE PROBLEM

My solution uses that MaxHeap. Basically, it goes over the array to build a hash table that has each number as key and their frequencies as value. Then, it will add all the key-value pair to the MaxHeap and pop them out one by one k time to add to the result array.

It is faster than the Heap approach suggested on Leetcode. The suggested solution on LeetCode also uses a heap, but it uses the min heap, then, after k times of adding the pair to the heap, it will add and pop at the same time to make sure at all time, the heap always contains k max elements (because the (k + 1)th is popped out immediately). However, it will add n time and pop n-k time. Each time it adds or pops, it needs logN time. So, the time it needs is nlogN.

My algorithm needs nLogN to add in the constructor, and kLogN to pop out. It will work faster if k is much smaller than n.

However, it doesn't improve the big O much. The Leetcode solution also suggests QuickSelect, which I will try next.

Revised by ChatGPT

My solution employs a MaxHeap to efficiently find the top K frequent elements in an array. The process begins by iterating through the array to construct a hash table, where each key represents a unique number and its corresponding value denotes the frequency of that number. Subsequently, all key-value pairs are added to the MaxHeap.

The primary difference between my solution and the one suggested on LeetCode lies in the choice of heap. While the LeetCode solution utilizes a MinHeap to maintain the k most frequent elements, my approach uses a MaxHeap. In the LeetCode solution, each insertion into the MinHeap is followed by a removal if the heap size exceeds k, ensuring that only the k most frequent elements are retained. This approach results in n insertions and n-k removals, each requiring O(logN) time, leading to a total time complexity of O(nlogN).

In contrast, my solution involves adding all elements to the MaxHeap in the constructor, which takes O(nlogN) time, and then extracting the top k elements, which takes O(klogN) time. This approach is more efficient when k is significantly smaller than n, as the extraction phase is faster. However, the overall time complexity remains O(nlogN), similar to the MinHeap approach.

Next, I plan to explore the QuickSelect algorithm as an alternative method, which has the potential to offer improved performance.