FIND ALL REPEATING AND NON-REPEATING ELEMENT
In programming, identifying repeating and non-repeating elements in an array is a common problem with practical applications in data analysis, optimization, and more. This task involves separating elements based on their occurrence count, making it an essential exercise in mastering data structures and algorithms.
How to Solve the Problem?
- Input: Take an array of integers.
- Process:
- Use a hash map to store the frequency of each element.
- Traverse the array and update the count of each number in the hash map.
- Output:
- Traverse the hash map to identify and print:
- Elements with a count greater than 1 (repeating).
- Elements with a count equal to 1 (non-repeating).
- Traverse the hash map to identify and print:
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int n=sc.nextInt();
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
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);
}
}
System.out.print("repeating elements");
for (Map.Entry<Integer, Integer> e : map.entrySet())
{
if(e.getValue()>1){
System.out.print(e.getKey());
}
}
System.out.println("non-repeating");
for (Map.Entry<Integer, Integer> e : map.entrySet())
{
if(e.getValue()==1){
System.out.print(e.getKey());
}
}
}
}
Applications of Finding Repeating and Non-Repeating Elements
- Data cleaning in databases.
- Detecting duplicates in lists.
- Problem-solving in competitive programming.
No comments:
Post a Comment