Wednesday, 2 December 2015

How Find out duplicate number between 1 to N numbers - Java Program

We have numbers from 1 to n  and one number is duplicate. Now we will find out duplicate number in given list. For this we will use formula sum of 1....n numbers.Firstly we will calculate the sum of list and sum of 1.... n number. Now difference between sum of list and sum of 1... n is equal to duplicate number .

sum of 1... n number = n*(n+1)/2

package com.javaproficiency;

import java.util.ArrayList;
import java.util.List;

public class FindDuplicateNumber {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < 10; i++) {
FindDuplicateNumber duplicateNumber = new FindDuplicateNumber();
System.out.println(" duplicate number ="+ duplicateNumber.getDuplicateNumber(list));

public  int getDuplicateNumber( ArrayList<Integer> list){

int size = list.size()-1;
int totalSum = (size*(size+1))/2;
int duplicateNumber = getSumOfList(list)- totalSum ;
return duplicateNumber;

public int getSumOfList( ArrayList<Integer> list){
int sum =0;
for (Integer num : list) {
sum += num;
return sum;


Output :

 duplicate number =5

No comments:

Post a Comment