Skip to content

Instantly share code, notes, and snippets.

@aniketmlk6
Created June 1, 2021 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aniketmlk6/45953a86a219a55f4f282fd7cf950b0a to your computer and use it in GitHub Desktop.
Save aniketmlk6/45953a86a219a55f4f282fd7cf950b0a to your computer and use it in GitHub Desktop.
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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment