Count More than n/k Occurences GFG SOlution

Given an array arr[] of size N and an element k. The task is to find all elements in array that appear more than n/k times.

Example 1:

Input:
N = 8
arr[] = {3,1,2,2,1,2,3,3}
k = 4
Output: 2
class Solution 
{
    //Function to find all elements in array that appear more than n/k times.
    public int countOccurence(int[] arr, int size, int k) 
    {
        // your code here,return the answer
        
        HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
        int count=0;
        for(int i=0;i<size;i++){
            if(!hm.containsKey(arr[i])){
                hm.put(arr[i],1);
            }
            else{
                int value=hm.get(arr[i]);
                if(value!=0){
                hm.put(arr[i],value+1);
                }
                
                if(value+1>size/k ){
                    count++;
                    hm.put(arr[i],0);
                }
                
            }
        }
        return count;
    }
}

Disclaimer: This problem() is originally created by GeeksforGeeksCodesagar only provides a solution for it. This solution is only for Educational and learning purposes.

Leave a Comment