Find Least Frequent Element
This program finds the least frequent element in an array.
Problem Statement
Write a Java program to find the least frequent element in an integer array.
Source Code
| 1 | import java.util.HashMap; |
| 2 | public class LeastFrequentElement { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Least Frequent Element"); |
| 5 | int[] arr = {1,2,2,3,3,3,4}; |
| 6 | HashMap<Integer,Integer> freq = new HashMap<>(); |
| 7 | for(int num:arr){ |
| 8 | freq.put(num,freq.getOrDefault(num,0)+1); |
| 9 | } |
| 10 | int minFreq=Integer.MAX_VALUE, element=-1; |
| 11 | for(int key:freq.keySet()){ |
| 12 | if(freq.get(key)<minFreq){ |
| 13 | minFreq=freq.get(key); |
| 14 | element=key; |
| 15 | } |
| 16 | } |
| 17 | System.out.println("Least frequent element: "+element+" occurs "+minFreq+" times"); |
| 18 | } |
| 19 | } |
Program Output
Eduinq Least Frequent Element Least frequent element: 1 occurs 1 times
Explanation
A HashMap stores the frequency of each element, and a loop scans the map's keys tracking the smallest frequency seen, demonstrating how to find the least frequent element in an array.