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

Close