✅Most occurring elements
Most occurring elements easy asked in interviews by 1 company Time Limit: 2 sec Memory Limit: 128000 kB
Problem Statement:
Given an integer array of size n. Print the three most occurring element. print them in order of their number of occurrence. If the number of occurrence is same then print the smaller number before. Input First line contains n. Next line contains n space separated integers.
Constraints 3 <= n < = 105 1 <= arr[i] <= 105 Output Output three integers. if there are not enough integers then print -1 for that place. Example Input: 6 1 2 1 2 2 1
Output: 1 2 -1
Explanation: number of occurrence of 1 = 3 number of occurrence of 2 = 3 so 1 is printed before 2. there are only 2 elements so we print -1 as third number.
link:https://my.newtonschool.co/playground/code/vgww7sajxmd8/
```java
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HashMap<Integer,Integer>tm=new HashMap<>();
for(int i=0;i<n;i++){
int a=sc.nextInt();
if(tm.containsKey(a)){
int freq=tm.get(a);
tm.put(a,freq+1);
}else{
tm.put(a,1);
}
}
int m1=-1;
int m2=-1;
int m3=-1;
int i=-1,j=-1,k=-1;
if(tm.size()>0){
for(Integer t:tm.keySet()){
if(tm.get(t)>m1){
m1=tm.get(t);
i=t;
}
}
tm.remove(i);
}
if(tm.size()>0){
for(Integer t:tm.keySet()){
if(tm.get(t)>m2){
m2=tm.get(t);
j=t;
}
}
tm.remove(j);
}
if(tm.size()>0){
for(Integer t:tm.keySet()){
if(tm.get(t)>m3){
m3=tm.get(t);
k=t;
}
}
tm.remove(k);
}
System.out.println(i+" "+j+" "+k);
}
}
```
Last updated