Hashmap Sorting Solution
This is the solution I came up with initially. It uses a hashmap where the key is the number and the value is its frequency. Then, the frequencies are turned into a list, which is sorted from highest to lowest. The top frequencies are found, and then we go back to the hashmap and find the corresponding keys.
- Time complexity: because of sorting
- Space complexity: ?
Max Heap
Bucket Sort
The idea of this is to use create an array where the index is frequency and the numbers is the value. So, for something like [1,1,1,2,2,2,3,4,4,100]
, you would have:
Index (Freq) | Value (Num) |
---|---|
1 | [100] |
2 | [4] |
3 | [1,2] |
4 | None |
… | … |
10 | None |
This makes stuff easier because it’s bounded by the length of the original list, and you can just go by frequency from the end of the map until you find the top frequencies.
- Time complexity: s
- Space complexity: , we are creating an array/hashmap to help us.