Here is a java program to find duplicate elements in an integer array. Given an array of integers(which may contains duplicate elements), we have to print all duplicate elements of array once. To find duplicate elements, we will count the frequency of each elements of array and store it in a Map. If frequency of any element is id more than 1, then it is a duplicate element otherwise it is a unique element.
Input Array 1 7 3 2 1 6 4 2 Duplicate Elements 1 2
Algorithm to find duplicate elements in Array
- Declare an integer array "inputArray" for storing input array elements.
- Declare a Map
to store the frequency of elements of inputArray. - Using for-each loop, traverse input array and for each element check whether element exists in Map or not.
- If present in map, increment it's count, other wise create a new entry in Map with count as 1.
- For each key-value entry in Map, check whether value is > 1, If true then corresponding key is a duplicate element otherwise unique element.
Java program to find duplicate elements
package com.tcc.java.programs; import java.util.*; public class DuplicateElements { public static void main(String args[]) { int count, i; int[] inputArray = new int[500]; Map<Integer,Integer> map = new HashMap<Integer, Integer>(); Scanner in = new Scanner(System.in); System.out.println("Enter number of elements"); count = in.nextInt(); System.out.println("Enter " + count + " elements"); for(i = 0; i < count; i++) { inputArray[i] = in.nextInt(); } // Count frequency of elements in array for(Integer val: inputArray){ if(map.containsKey(val)){ // Increment counter map.put(val, map.get(val)+1); } else { map.put(val, 1); } } // Check for duplicate element System.out.println("Duplicate Elements\n"); Set<Integer> keys = map.keySet(); for (Integer key : keys){ if(map.get(key) > 1){ System.out.print(key + " "); } } } }Output
Enter number of elements 6 Enter 6 elements 3 6 2 3 1 1 Duplicate Elements 1 3
Recommended Posts