Find all array elements occurring more than ⌊N/3⌋ times.
Q. Find all array elements occurring more than ⌊N/3⌋ times.
Solution in java :
// find elements in the array that occurs more than n/3 times in array
// 19 march 2021
// T.U.F Question
import java.util.*;
class cf
{
static void calc(int[] arr ) {
int len = arr.length;
//first solution
// HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
// for(int i=0;i<len;i++) {
// if(!map.containsKey(arr[i])){
// map.put(arr[i],1);
// }
// else{
// map.put(arr[i],map.get(arr[i])+1);
// }
// }
// System.out.println(map);
// map.forEach((key,value)-> {
// if(value>len/3)
// System.out.println(key);
// });
int cnt1 = 0;
int cnt2 = 0;
int num1 = -1;
int num2 = -1;
for(int i=0;i<len;i++) {
if(arr[i] == num1){
cnt1++;
}
else if(arr[i] == num2){
cnt2++;
}
else if(cnt1 == 0){
num1 = arr[i];
}
else if(cnt2 == 0){
num2 = arr[i];
}
else {
cnt1--;
cnt2--;
}
}
System.out.println(num1);
System.out.println(num2);
//also check the frequency of num1 and num2 in array. Not always the answer will be correct.
// if freq(num1 or num2) < n/3 dont print it
// I am not implementing that code to check frequency.
}
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
try
{
int arr[] = {1,1,1,1,1,2,2,2,3,3,3,3};
calc(arr);
}
catch(Exception e){
return;
}
}
}
Output :
Input: arr[] = {5, 3, 5}
Output: 5
Explanation:
The frequency of 5 is 2, which is more than N/3( = 3/3 = 1).
Input: arr[] = {7, 7, 7, 3, 4, 4, 4, 5}
Output: 4 7
Explanation:
The frequency of 7 and 4 in the array is 3, which is more than N/3( = 8/3 = 2).