Question: Find the highest/lowest frequency element.If there are multiple elements that have the highest frequency or lowest frequency then pick the smallest element.
Coding Ninjas Problem link
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
public class Solution {
public static int[] getFrequencies(int[] v) {
int n = v.length;
return frequency(v, n);
}
public static int[] frequency(int[] arr, int n) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
TreeSet<Integer> maxFreqElements = new TreeSet<>();
TreeSet<Integer> minFreqElements = new TreeSet<>();
int maxFreq = 0, minFreq = n;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int count = entry.getValue();
int element = entry.getKey();
if (count > maxFreq) {
maxFreqElements.clear();
maxFreqElements.add(element);
maxFreq = count;
} else if (count == maxFreq) {
maxFreqElements.add(element);
}
if (count < minFreq) {
minFreqElements.clear();
minFreqElements.add(element);
minFreq = count;
} else if (count == minFreq) {
minFreqElements.add(element);
}
}
int[] res = new int[2];
res[1] = minFreqElements.first(); // Smallest element with minimum frequency
if (maxFreqElements.size() > 1) {
res[0] = maxFreqElements.first(); // Smallest element with maximum frequency
} else {
res[0] = maxFreqElements.pollFirst();
}
return res;
}
}
No comments:
Post a Comment