# Top K Frequent Elements Leetcode Solution

## Top K Frequent Elements Leetcode Problem :

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

## Top K Frequent Elements Leetcode Solution :

### Constraints :

• 1 <= nums.length <= 105
• -104 <= nums[i] <= 104
• k is in the range [1, the number of unique elements in the array].
• It is guaranteed that the answer is unique.

### Example 1:

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

Intuition :

Intution is to make a HashMap and then use arrayList to add highest frequencies and then store k highest frequeny in another list and at last iterate through the map and add key to the answer array using values that we stored in list2.

Approach :

1. First we made a hash Map in which we stored elements of array as key and their frequencies as value in map.
2. Now we made a arrayList in which we added all the values(i.e frequencies) of elements of array.
3. Now we sorted array in reverse order beacuse we need to get k highest frequency elements .
4. Now we made another list in which we added frequencies of k elements .
5. Now because we need to return answer in an array type so we created an array named : “ans”.And we used a pointer j to keep on adding Key from map to answer array.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others