Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

K Most Frequent Elements

Moderate
0/80
Average time to solve is 10m
profile
Contributed by
41 upvotes
Asked in companies
UberFacebookOracle

Problem statement

You are given an Integer array ‘ARR’ and an Integer ‘K’.


Your task is to find the ‘K’ most frequent elements in ‘ARR’. Return the elements in any order.


For Example:

You are given ‘ARR’ = {1, 2, 2, 3, 3} and ‘K’ = 2. 

The answer will {2, 3} as 2 and 3 are the elements occurring most times.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line contains two space-separated integers, ‘N’ and ‘K’, representing the size of ‘ARR’ and the given integer ‘K’, respectively.

The second line contains ‘N’ space-separated integers representing the elements of ‘ARR’.
Output Format:
The only line contains the ‘K’ most frequent elements in ‘ARR’.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Sample Input 1:
5 2
1 2 2 3 3 
Sample Output 1:
2 3
Explanation of Sample Input 1:
The answer will {2, 3} as 2 and 3 are the elements occurring the most number of times.
Sample Input 2:
2 2
1 2 
Sample Output 2:
1 2
Constraints:
1 <= 'N' <= 10^5
1 <= 'K' <= Number of unique elements in ‘ARR’
1 <= 'ARR[i]' <= 10^6

Time Limit: 1 sec
Full screen
Console