Java Program to find out duplicate number in an Array

Problem statement : In an array 1-100, many numbers are duplicates, how do you find it?

we can loop over array and put the values in a map to find out duplicate numbers with the number of time they repeat them selves.

            int[] numbers = new int [100];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
       
        for(int i=0;i<100;i++){
            int temp = numbers[i];
            Integer count = map.get(temp);
            map.put(temp, (count == null) ? 1 : count + 1);
        }
       
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println(“Key : ” + entry.getKey() + ” Value repetition time: “
                + entry.getValue());
        }

The solution I proposed gives you the freedom of printing you data in several way or store the data in a manner which is most easy to retrieve. ie create a map for each number and save them against the key.

2 thoughts on “Java Program to find out duplicate number in an Array

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s