Let’s say you are given to solve the following question:
Find the Least frequent element in a list in Java.
Note: If you find multiple such numbers in the array, then print any one of them.
Example 1: Input: array = [10,10,11,12,12,12] Output: least frequent element is 11
Example 2: Input: array = [10,10,11,12,12,12,13] Output: least frequent element is 11
Try to solve it on your IDE before reading further.
If you have solved it, congratulations, you can skip the following hints.
However, in case you are stuck, these are some hints for you.
Hint 1
Understanding Overall Idea :
Step 1:
In order to find the least frequent element, we need to traverse through the array and then store the frequency of each element in a hashmap.
Step 2:
For this hashmap, get the element for whom, the frequency is minimum.
Try it again!
COMPLETE SOLUTION 1 [EASY TO UNDERSTAND]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
The solution above is easy to understand. However, it may not be using some basic design principles. The solution given below is better from a design perspective.
COMPLETE SOLUTION 2
static int rarestElement(int[] arr) | |
{ | |
HashMap<Integer, Integer> hash = new HashMap<>(); | |
// saving frequency for each element in hashmap | |
for (int element : arr) { | |
if (hash.containsKey(element)) { | |
int value = hash.get(element); | |
value++; | |
hash.put(element, value); | |
} else { | |
hash.put(element, 1); | |
} | |
} | |
// getting minimum | |
int min_Value = hash.get(arr[0]); | |
int minKey = arr[0]; | |
for (int key : hash.keySet()) { | |
if (hash.get(key) < min_Value) { | |
min_Value = hash.get(key); | |
minKey = key; | |
} | |
} | |
return minKey; | |
} | |
public static void main(String[] args) { | |
int[] arr = {10,10,11,12,12,12}; | |
System.out.println("least frequent element is "+rarestElement(arr)); | |
} |
I hope this article helped you.
In case the solution is not clear to you, I suggest you take a live 1:1 lesson on this subject from me. I am an Oracle-certified tutor who would love to teach this stuff to you.
Aniket Malik