Intuition
in order to solve this problem first we have to travel every element in this array and pick up the highest frequent occurrences number which is designate by k.
Approach
first we implement a dictionary to store the number and the frequency then we travel all the elements in array. If the number is included the frequency should plus 1.if the number is not included the frequency should be set to 1.then set a tuple to recive all the numbers and its frequency.in order to obtain the top k highest frequency numbers we arrange them in descending order.At last we can travel top k highest frequenct numbers to get the result.
Complexity
- Time complexity:
the first setp travel numbers will take O(n) and the second step travel will take O(n) the third step due to the properties of the sort function in python which is implemented timesort algorithm it will take O(nlog(n)) and the forth step will take O(k).So the final time complexity is O(nlog(n)).
- Space complexity:
To maintain the hash table it will take O(n) space complexity
Code
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
frequency={}
for num in nums:
if num in frequency:
frequency[num]+=1
else:
frequency[num]=1
element_fre=[(num,freq) for num,freq in frequency.items()]
element_fre.sort(key=lambda x: x[1],reverse=True)
result=[element for element,_ in element_fre[:k]]
return result