Write a Program to find duplicate number between 1 to N Numbers [Java interview]

Write a Program to find duplicate number between 1 to N Numbers

This article will help you to understand “Java Program to find duplicate number.”

Here we have an array from 1 to N with one duplicate number.

e.g we have array from 1 to 10 and 2 is repeated once in this array. Then we need to find that 2 is a duplicate number in given array.

Java Program to find duplicate number between 1 to N Numbers

package com.codenuclear;

public class FindDuplicateNumber {

		public int findDuplicateNumber(int inputArray[],int N){
			
			int sum = getSum(inputArray);
			
			int dupNo = sum - (N*(N+1)/2);
			return dupNo;
		}
		
		public int getSum(int numbers[]){
			
			int sum = 0;
			for(int num:numbers){
				sum += num;
			}
			return sum;
		}
		
		public static void main(String args[]){
			
			int N = 10;
			
			// Below array is from 1 to 10 and 2 is repeated once.
			int givenArray[] = {5,2,9,8,2,3,10,1,7,6,4};
			
			FindDuplicateNumber obj = new FindDuplicateNumber ();
			
			System.out.println("Duplicate Number is : "+obj.findDuplicateNumber(givenArray,N));
		}
}

Output Duplicate Number is : 2