The Most Frequent Value

import java.io.*;
import java.util.*;

public class FrequentValue {

public static void main(String[] args){

int n[] = {6, 6, 2, 6, 4, 2, 2, 6, 2 };
freqVal(n);

}

public static int freqVal(int[] n) {
    
int[] count = new int[10000];

int maxCount = 0;
int val = 0;

for(int i = 0; i < n.length; i++) {
count[n[i]]++;
        
if(count[n[i]] > maxCount) {
maxCount = count[n[i]];
val = n[i];
        
           }
    
        }
    
    System.out.println(val);
    return val;

    }

}

Hi,

So my code prints the value in the array that shows up the most. One stipulation is that if more than one value appears the most, then print the value that appears closest to the start of the input. I thought this was the case when I tested it in my own IDE using my own values. However, when I use it on a practice problem in LeetCode , I get different results since it uses different test cases. I am not sure what the problem could be. Maybe doing it in this approach is wrong?


Solution 1:

One stipulation is that if more than one value appears the most, then print the value that appears closest to the start of the input

But your code doesn't guarantee that.

For example, given the input {6, 6, 2, 2, 2, 6}, your code will print 2 even though 6 is the one being closer to the start of the input.

So you should change this:

for(int i = 0; i < n.length; i++) {
    count[n[i]]++;
    if(count[n[i]] > maxCount) {
        maxCount = count[n[i]];
        val = n[i];
    }
}

To this:

// first do the counting
for(int i = 0; i < n.length; i++) {
    count[n[i]]++;
}
// then find the one which appears the most
for(int i = 0; i < n.length; i++) {
    if(count[n[i]] > maxCount) {
        maxCount = count[n[i]];
        val = n[i];
    }
}