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.
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

package com.java9co;
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