Find the overlapping sum of two arrays using C++

C++Server Side ProgrammingProgramming

In this problem, we are given two arrays arr1[] and arr2[] consisting of unique values. Our task is to find the overlapping sum of two arrays.

All elements of the arrays are distinct. And we need to return the sum of elements which are common for both arrays

Let’s take an example to understand the problem,

Input

arr1[] = {5, 4, 9, 2}, arr2[] = {6, 3, 9, 4}

Output

2

Explanation

The elements that are present in both arrays are 9 and 4.
The sum is 9 + 9 + 4 + 4 = 26

Solution Approach

A simple solution to the problem is traversing one array say arr1[] and for each element check if there is a matching value in another array. If any element matching the current value is found, then add both to the sum value.

This approach requires nesting of loops that leads to time complexity of the order O(N2).

Another approach to solve the problem is using hashing. We will create a hash table and store values of both the arrays in the table and keep the count of frequency of elements. Then add the value with occurrence frequency two. Return double of the sum value.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
int findCommonValSum(int A[], int B[], int n){
   unordered_map<int,int> hashTable;
   for(int i=0;i<n;i++){
      if(hashTable.find(A[i])==hashTable.end())
      hashTable.insert(make_pair(A[i],1));
      else
         hashTable[A[i]]++;

      if(hashTable.find(B[i])==hashTable.end())
         hashTable.insert(make_pair(B[i],1));
      else
      hashTable[B[i]]++;
   }
   int commSum = 0;
   for(auto itr = hashTable.begin(); itr!=hashTable.end(); itr++){
      if((itr->second)==2){
         commSum += (itr->first);
      }
   }
   return (commSum*2);
}
int main(){
   int A[] = { 5, 4, 9, 2 };
   int B[] = { 6, 3, 9, 4 };
   int n = sizeof(A) / sizeof(A[0]);
   cout<<"The sum of common values in the array are "<<findCommonValSum(A, B, n);
   return 0;
}

Output

The sum of common values in the array are 26
raja
Updated on 11-Feb-2022 12:51:25

Advertisements