CC-10 : Find most frequent integer after k.
Description:
Given an integer k and an array of integers arr, count the frequency of characters that occur immediately after index k in arr. Return the integer that occurs most frequently after k.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| arr={2,3,2,4,2,2,3,2,1}; k=2; |
Most Common Element after 2 is 3 |
| arr={2,3,2,4,2,2,3,2,1,2,2,2}; k=2; |
Most Common Element after 2 is 2 |
Pseudocode:
| The java method should accept following input parameters: arr (integer array), k (integer). |
| Initialize a variable cntMap of type HashMap< Integer,Integer> to hold integers occurring immediately after k and their frequency of occurring in arr. |
| Initialize maxCnt to 0. Initialize maxInt to Integer.MIN_VALUE. |
| Iterate through arr using a for loop with idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
If cntMap does not contain key equal to arr[idx+1]:
Add key arr[idx+1] and add value 1 to cntMap.
If cntMap contains key equal to arr[idx+1]:
Add key arr[idx+1] and add value equal to current value of key arr[idx+1], incremented by 1 to cntMap.
If value corresponding to key arr[idx+1] is greater than maxCnt:
Set maxCnt= value corresponding to key arr[idx+1].
Set maxInt= arr[idx+1].
|
| After above loop completes successfully, maxInt contains the most frequent integer after k in arr. Return maxInt. |
Code:
public int hashMapMostFreqAfterKey(int[] arr, int k) throws Exception{
HashMap< Integer,Integer> cntMap=new HashMap< Integer, Integer>();
int maxCnt=0; int maxInt=Integer.MIN_VALUE;
for (int idx=0; idx < arr.length; idx++) {
if ((arr[idx]==k)&& (idx+1 < arr.length)){
cntMap.put(arr[idx+1], cntMap.getOrDefault(arr[idx+1], 0)+1);
if (cntMap.get(arr[idx+1]) > maxCnt) {
maxCnt=cntMap.get(arr[idx+1]);
maxInt=arr[idx+1];
}
}
}
return maxInt;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |