Created
June 1, 2021 14:55
-
-
Save aniketmlk6/45953a86a219a55f4f282fd7cf950b0a to your computer and use it in GitHub Desktop.
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
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