Tag Archives: Count Duplicate Element

Count Duplicate Pairs of Integer in a given array (Hacker Rank Interview Questions)

Input: Integer array with 0 or more repeated values.
Output: Total number of duplicate numbers present in the given array

The use of Hash set can be done in order to solve this by traversing each element and adding it into the set, later on they are checked for repetitive addition (i.e. we make sure that the numbers were not included already!)

Step 1: Create 2 hash sets. 1 is for all the elements and the other is for the duplicate elements.

Step 2: Loop over each element in the given array

Now, for each element:

a. Check whether element is in the Hash set

b. If yes, then add it to duplicate set

c. If no, then add it to normal hash set

Step 3: output the size of duplicate hash set

Below is the code in java for the above problem.

You can have below code from GIT.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git

 

HackerRankProjectStructure

Below is the code:

import java.util.HashSet;

public class CountDuplicates {
	 static int countDuplicates(int[] numbers) {
		 HashSet<Integer> set = new HashSet<Integer>();
		 HashSet<Integer> duplicateSet = new HashSet<Integer>();
		 
		 for(int i=0;i<numbers.length;i++){
				if(set.contains(numbers[i])){
					duplicateSet.add(numbers[i]);
				}else{
					set.add(numbers[i]);
				}
			}
		 
		 return duplicateSet.size();
	 }
	 
	 public static void main(String p[]){
		int a[]={20,20,20,30,40,50,60,90,80,90,100};
		System.out.println("Total Number having duplicate Count:"+countDuplicates(a));
	 }

}

The output of the above code:

Input:
{20,20,20,30,40,50,60,90,80,90,100};

Output:
Total Number having duplicate Count:2

You can have above code from GIT.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git