Find out Duplicate Number between 1 to n numbers in java

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

Duplicate Number in Java
Fig: Duplicate Number

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

  1. Get numbers between 1 to n included a duplicate number.
  2. Add all numbers to get total.
  3. Get number count-1 entered by user.
  4. Sum first n natural numbers up to count-1.
  5. Subtract total-sum
  6. Print duplicate number

Based on above easy steps, we can implement it in Java very fast.

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 integer value using Integer.parseInt().

duplicate number between 1 to n numbers in java
Fig: Duplicate number between 1 to n numbers in java

So we achieved our desired result.