Sunday, April 12, 2020

Add Occurrence Of Twice (100 Marks)

You will be given an array and you need to find the elements occurring twice and add them.

Input Format
You will be taking a number as an input stdin which tells about the length of the array. On another line, array elements should be there with single space between them.

Constraints
1 <= L <= 1000
1 <= Ai <= 1000

Output Format
You need to print the sum of the numbers occurring twice.

Sample TestCase 1
Input
12
9 8 7 7 8 6 5 4 6 5 1 2
Output
26
                                              

  Solution:
import java.io.*;
import java.util.*;
public class CandidateCode {
        public static void Count(int arr[], int n){
              Map<Integer, Integer> map = new HashMap<>();
              for(int i=0; i<n; i++){
                    if(map.containsKey(arr[i]))
                          map.put(arr[i], map.get(arr[i])+1);
                    else
                          map.put(arr[i],1);
               }
              int sum=0;
             for(Map.Entry<Integer, Integer> entry : map.entrySet()){
                   if(entry.getValue()==2)
                        sum+=entry.getKey();
                    // System.out.println(entry.getKey() + " : " + entry.getValue());
              }
         System.out.print(sum);
       }
      public static void main(String args[] ) throws Exception {
            Scanner sc = new Scanner(System.in);
            int size = sc.nextInt();
            int arr[] = new int[size];
            for(int i=0; i<arr.length; i++)
            arr[i]=sc.nextInt();
            Count(arr,size);
       }
}

No comments:

Post a Comment