Problem find the frequency of number in array using HashMap
In this post, we will explore how to find the frequency of each number in an array using a HashMap in Java. This approach is efficient and easy to implement. Let’s break down the problem with code and explanation.
Input:
6
[2,5,7,1,2,5]
Output:
1 1
2 2
5 2
7 1
import java.util.*;
public class hello(){
public static void main(String args[]){
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int n=sc.nextInt();
for(int i=0;i<n;i++){
int temp=sc.nextInt();
if(map.containsKey(temp)){
int value=map.get(temp);
map.replace(temp,++value);
}
else{
map.put(temp,1);
}
}
for (Map.Entry<Integer, Integer> e : map.entrySet())
System.out.println(e.getKey() + " "+ e.getValue());
}
}
Explanation
Input:
- First, the program reads the size of the array,
n. - Then, it reads
nnumbers into the array.
- First, the program reads the size of the array,
Using a HashMap:
- A HashMap is used to store the numbers as keys and their frequencies as values.
- If a number is already present in the map (
map.containsKey(temp)), its frequency is incremented. - If it’s not present, it is added to the map with an initial frequency of 1.
Output:
- Finally, the program iterates through the
HashMapand prints each key (number) with its corresponding value (frequency).
- Finally, the program iterates through the
Example Input and Output
Input:
Process:
- Numbers in the array: [2, 5, 7, 1, 2, 5]
- After processing:
- 1 appears once.
- 2 appears twice.
- 5 appears twice.
- 7 appears once.
Output:
Edge Cases to Consider
Array with Repeated Numbers: The program works efficiently even if all numbers are the same. Input:
[5, 5, 5, 5]
Output:Empty Array: If
n == 0, the program will output nothing, which is the correct behavior. However, you can add a check to handle this explicitly.Negative Numbers: The program handles negative numbers naturally, as
HashMapkeys can be any integer.
Conclusion
Using a HashMap to find the frequency of numbers in an array is both intuitive and efficient. This approach is suitable for arrays of any size and works seamlessly with positive, negative, or repeated numbers.
No comments:
Post a Comment