Sum the common elements | Practice | GeeksforGeeks

You are given two arrays of size n1 and n2. Your task is to find all the elements that are common to both the arrays and sum them print them in the order as they appear in the second array. If there are no common elements the output would be 0.
Note: The arrays may contain duplicate elements. However, you need to sum only unique elements that are common to both arrays.
Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two three lines of input. The first line contains n1 and n2 separated by a space. The second line contains elements of arr1. The third line contains elements of arr2.
Output Format:
For each testcase, in a new line, print the common sum.
Your Task:
Since this is a function problem, you don't need to take any input. Just complete the provided function commonSum that takes two arrays as input.
Constraints:
1 <= T <= 100
1 <= n1,n2 <= 1000
1 <= arr1i,arr2i <= 109
Example:
Input:
1
5 6
1 2 3 4 5
2 3 4 5 6 7
Output:
14
0
ankitparashxr3 months ago
java
int sum = 0;    Set<Integer> s = new HashSet<>();        for(int val:arr1)    {        s.add(val);    }    for(int val:arr2)    {        if(s.contains(val))        {            sum+=val;            s.remove(val);        }    }        return sum;
0
ankitparashxr3 months ago
java
int sum = 0;     HashMap<Integer,Integer> hm = new HashMap<>();     for(int val:arr1)     {         if(hm.containsKey(val))         {             hm.put(val,hm.get(val)+1);         }         else         {             hm.put(val,1);         }     }          for(int val:arr2)     {         if(hm.containsKey(val) && hm.get(val)>0)         {             sum+=val;             hm.remove(val);         }     }     return (long)sum;
0
padmaraju0843 months ago
def get_common(set1,set2):   comm=set1 & set2    le=len(comm)   if le==0:       return "0"   else:       sum_1=sum(comm)       return sum_1   def get_sets(m,n):   set1=set()   for value1 in range(m):       a=int(input())       set1.add(a)          set2=set()       for value2 in range(n):       b=int(input())       set2.add(b)          out=get_common(set1,set2)   return out
 
t=int(input())for i in range(t):   m,n=input().split(" ")   m,n=int(m),int(n)   out=get_sets(m,n)   print(out) 
+1
devreujjval774 months ago
//Java Solution with 0.6 TimeTaken using a HashSet
 
class Geeks
{
    public static long commonSum(int arr1[], int arr2[])
    {
       //Your code here
       int sum = 0;
       Set<Integer> set = new HashSet<>();
       
       //Using foreach loop on an array to add all-
       //its unique elements to the HashSet
       for(int i: arr1){
           set.add(i);
       }
       
       //Looping through second array and
       //checking for the element in the HashSet
       for(int i: arr2){
           if(set.contains(i)){
               //adding the values on match and removing
               //the element from Hashset to avoid duplicates
               sum+=i;
               set.remove(i);
           }
       }
       return sum;
    }
}
 
0
badgujarsachin836 months ago
 public static long commonSum(int arr1[], int arr2[])
    {
       //Your code here
       int sum=0;
        HashSet<Integer> h=new HashSet<>();
        for(int it:arr1){
            h.add(it);
        }
        for(int it:arr2){
            if(h.contains(it)){
                h.remove(it);
                sum+=it;
            }
        }
        return sum;
    }
0
siddhartha agarwal8 months ago
siddhartha agarwal
//Java use only one hashSet
class Geeks{    public static long commonSum(int arr1[], int arr2[])    {        HashSet<integer> h= new HashSet<>();         for(int i:arr1)            h.add(i);         int sum=0;            for(int i:arr2)            if(h.contains(i))            {                h.remove(i);                sum+=i;            }             return sum;       //Your code here    }}
0
Navin Ranjan1 year ago
Navin Ranjan
java easy solutionHashSet<integer> hs1=new HashSet<>();       HashSet<integer> hs2=new HashSet<>();       for(int x:arr1)            hs1.add(x);         for(int x:arr2)            hs2.add(x);         long sum=0;        for(int x:hs2)            if(!hs1.add(x))                sum+=x;         return sum;
0
Harsh2 years ago
Harsh
public static long commonSum(int arr1[], int arr2[])    {       Set<integer> set1 = new HashSet<>();       Set<integer> set2 = new HashSet<>();       for(int i=0;i<arr1.length;i++) set1.add(arr1[i]);="" for(int="" i="0;i&lt;arr2.length;i++)" set2.add(arr2[i]);="" set2.retainall(set1);="" int="" sum="0;" for(int="" x="" :="" set2)="" sum+="x;" return="" sum;="" }="">
0
Anant Krishan Joshi2 years ago
Anant Krishan Joshi
class Geeks{    public static long commonSum(int arr1[], int arr2[])    {       //Your code here        Set<integer> a = new HashSet<integer>(arr1.length);        Set<integer> b = new HashSet<integer>(arr2.length);        for(int i=0;i<arr1.length;i++) a.add(arr1[i]);="" for(int="" i="0;i&lt;arr2.length;i++)" b.add(arr2[i]);="" integer="" sum="0;" set<integer=""> s = new HashSet<integer>(a);       s.retainAll(b);       Iterator<integer> it = s.iterator();       while(it.hasNext()) {        Integer setElement = it.next();        sum+=setElement;    }    return sum;    }
0
Devarshi Singh3 years ago
Devarshi Singh
class Geeks{
    public static long commonSum(int arr1[], int arr2[])
    {
        long sum=0;
        Set<integer> a1 = new HashSet<integer>();
        Set<integer> a2 = new HashSet<integer>();
        for(int i=0;i<arr1.length;i++) a1.add(new="" integer(arr1[i]));="" for(int="" j="0;j&lt;arr2.length;j++)" a2.add(new="" integer(arr2[j]));="" a1.retainall(a2);="" can't="" use="" iterator="" here="" for(integer="" a:="" a1)="" {="" sum+="a;//Unboxing" and="" type="" conversion="" }="" return="" sum;="" }="" }="">
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.