Find out duplicate number between 1 to n numbers in java is generally ask in interviews.
Here we are going to find a duplicate number between 1 and n.
n is any user given number.
We have to check which number is duplicate.
For example
In above figure first row contains number 12 two times so number 12 is duplicate number.
In second row number 6 is duplicate.
In third row number 7 is duplicate
This problem can solved by sum of numbers and sum of natural numbers
lets see step by step process to develop this problem in easy and quick way
Duplicate number between 1 to n
lets see our Algorithm
- Get numbers between 1 to n included a duplicate number.
- Add all numbers to get total.
- Get number count-1 entered by user.
- Sum first n natural numbers up to count-1.
- Subtract total-sum
- Print duplicate number
Based on above easy steps, we can implement it in Java very fast.
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 | public class DuplicateBetween1ToN { public static void main(String[] args) { //1. Get numbers between 1 to n included a duplicate number. /*numbers are entered using command line argument and stored in args[]*/ int total = 0; //2. Add all numbers to get total for (String arg : args) { total += Integer.parseInt(arg); } //3. Get number count-1 entered by user. int n = args.length - 1; //4. Sum first n natural numbers up to count-1 int sumOfN = n * (n + 1) / 2; //5. Subtract total-sum int duplicateNo=total-sumOfN; //6. Print duplicate number System.out.println("Duplicate Number is "+duplicateNo); } } |
Compilation and Result
compile Java program and while running java program we are passing numbers as command line argument included duplicate number.
Command line argument are stored in args String array.
While adding numbers string numbers are converted to an integer values using Integer.parseInt()
.

Here we solved to find out duplicate number between 1 to n numbers in java in easy way.
Hope you learned from this post.