What to learn with Java
Today I want to publish one java exercise, which I got today in the interview. It was my old idea to set up on my blog category with java exercises. So it’s a good time to start doing this. All exercises will be published with solutions, so you will be able to see the results or to suggest your own ideas in the comments.

Task:

You need to find the most frequent element in an array. The array consists of integers. For example, if you have sequence of such integers: 1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2, the solution will be the string:

The winner is number 3, its frequency of occurrence is 6

Here is my solution:

...
		int[] mas = {1,2,9,3,4,3,3,1,2,4,5,3,8,3,9,0,3,2};
		
		int maxKey = -1;
		int maxValue = -1;
		
		Map<'Integer', 'Integer'> pretenders = new HashMap<'Integer', 'Integer'>();
		
		int masSize = mas.length;
		
		for (int i = 0; i < masSize; i++) {
			if (!pretenders.containsKey(mas[i])) 
				pretenders.put(mas[i], 1);
			else
				pretenders.put(mas[i], pretenders.get(mas[i])+1);
		}
		
		for (Map.Entry<'Integer', 'Integer'> entry : pretenders.entrySet())
		{
		    if (entry.getValue() > maxValue) {
		    	maxKey = entry.getKey();
		    	maxValue = entry.getValue();
		    }
		}

		System.out.println("The winner is number "+maxKey+" its frequency of occurrence is "+maxValue);
...

So as you see, the most frequent number in the array is 3.

Try to solve this exercise by yourself. It will be great to see more efficient solution in the comments.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

  • Gik
    • Fruzenshtein

      Not bad =)

  • Chaker

    /* a solution 4 times faster (623881 nano seconds) :p */
    int[] n = new int[] {1,2,9,3,4,3,3,1,2,4,5,3,8,3,9,0,3,2}; int maxKey = 0;
    int maxCounts = 0;

    int[] counts = new int[n.length];

    for (int i=0; i < n.length; i++) {
    counts[n[i]]++;
    if (maxCounts < counts[n[i]]) {
    maxCounts = counts[n[i]];
    maxKey = n[i];
    }
    }
    System.out.println("The winner is number "+maxKey+" its frequency of occurrence is "+maxCounts);

    • Luis Costa

      but this solution don’t work with negative number!

  • Krithinarayanan Ganesh Kumar

    Integer[] mas = {1,2,9,3,4,3,3,1,2,4,5,3,8,3,9,0,3,2};

    Map count = new HashMap();

    Arrays.asList(mas)

    .stream()

    .forEach(key->count.put(key, count.getOrDefault(key,0)+1));

    Optional maxOccurance = count.keySet().stream()

    .reduce((key, nextKey)->count.get(key)>count.get(nextKey)?key:nextKey);

    maxOccurance.ifPresent(key -> System.out.println(“The winner is number “+key+” its frequency of occurrence is “+count.get(key)));

Close