Find out duplicate number between 1 to N numbers.

package com.java2novice.algos;
 
import java.util.ArrayList;
import java.util.List;
 
public class DuplicateNumber {
 
    public int findDuplicateNumber(List<Integer> numbers){
         
        int highestNumber = numbers.size() - 1;
        int total = getSum(numbers);
        int duplicate = total - (highestNumber*(highestNumber+1)/2);
        return duplicate;
    }
     
    public int getSum(List<Integer> numbers){
         
        int sum = 0;
        for(int num:numbers){
            sum += num;
        }
        return sum;
    }
     
    public static void main(String a[]){
        List<Integer> numbers = new ArrayList<Integer>();
        for(int i=1;i<30;i++){
            numbers.add(i);
        }
        //add duplicate number into the list
        numbers.add(22);
        DuplicateNumber dn = new DuplicateNumber();
        System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers));
    }
}
Share

Recent Posts

How to reverse Singly Linked List?

[crayon-6635aa00c6851898012033/] [crayon-6635aa00c685f157429264/] Output: Adding: 3 Adding: 32 Adding: 54 Adding: 89 3 32 54 89…

5 years ago

Find out middle index where sum of both ends are equal

You are given an array of numbers. Find out the array index or position where…

5 years ago

Write a singleton class in Java

Singleton class means you can create only one object for the given class. You can…

5 years ago

Write a java program to reverse a string?

1) Using StringBuffer class In this method, we use reverse() method of StringBuffer class to reverse the…

5 years ago

Write a java program to remove all white spaces from a string.?

1) Using replaceAll() Method. In the first method, we use replaceAll() method of String class…

5 years ago

Singly linked list implementation

Singly Linked Lists are a type of data structure. It is a type of list.…

5 years ago