Learn-dsa..in 30 days!



























CC-1 : Find Elements with highest and lowest Frequency.

Description:

Given an array containing integers, find the integers with highest and lowest frequency and return the same.

Test cases and expected outputs:

Input Parameters Expected outputs
arr[]={4,3,3,1,0,1}; Most Frequent Integer in array is : 3 Count: 2
Least Frequent Integer in array is : 4 Count: 1
arr[]={4,4,4,4}; Most Frequent Integer in array is : 4 Count: 4
Least Frequent Integer in array is : 4 Count: 4
arr[]={9,9,9,1,2,2,2}; Most Frequent Integer in array is : 9 Count: 3
Least Frequent Integer in array is : 1 Count: 1

Pseudocode:

The java method should accept following input parameters: arr (int array).
Initialize a variable hMap of type HashMap to hold the input integers and their frequencies.
Initialize variables mostFreq and mostFreqCnt to hold the most frequent int in arr and its frequency.
Initialize variables leastFreq and leastFreqCnt to hold the least frequent int in arr and its frequency.
Using a for loop, iterate through arr, using idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
if hMap does not already have a key arr[idx], set currFreq to 0.
Else get value corresponding to arr[idx] from hMap and increment it by 1 before setting it to currFreq.
If currFreq > mostFreqCount:
Set mostFreq=arr[idx].
Set mostFreqCnt=currFreq.
If leastFerq == arr[idx]:
Or If leastFreq < leastFreqCount:
Set leastFreq=arr[idx].
Set leastFreqCnt=currFreq.
After completion of above loop, mostFreq and mostFreqCnt contain the most frequent int in arr and its frequency. Similarly, leastFreq and leastFreqCnt contain the least frequent int in arr and its frequency. Set the value of above 4 variables in int array retVal. Return retVal.

Code:

public int[] arrayFindHighestAndLowestFreq(int[] arr) throws Exception{
	HashMap<Integer,Integer> hMap=new HashMap<Integer, Integer>();
	int mostFreq=0; int mostFreqCnt=Integer.MIN_VALUE;
	int leastFreq=0; int leastFreqCnt=Integer.MAX_VALUE;
	int currFreq=0;
	for (int idx=0; idx < arr.length; idx++) {
		currFreq=hMap.getOrDefault(arr[idx],0)+1;
		hMap.put(arr[idx],currFreq);
		if (currFreq > mostFreqCnt) {
			mostFreq=arr[idx];
			mostFreqCnt=currFreq;
		}
		if ((leastFreq==arr[idx])||(currFreq < leastFreqCnt)) {
			leastFreq=arr[idx];
			leastFreqCnt=currFreq;
		}			
	}
	
	int[] retArr=new int[4];
	retArr[0]=mostFreq; retArr[1]=mostFreqCnt;
	retArr[2]=leastFreq; retArr[3]=leastFreqCnt;
	return retArr;		
}

Click here to download and run code and test cases !