Non-overlapping sum of two sets

1

Given two arrays A[] and B[] of size n. It is given that both array individually contain distinct elements. We need to find sum of all elements that are not common.

Examples:

Input : A[] = {1, 5, 3, 8}
        B[] = {5, 4, 6, 7}
Output : 29
1 + 3 + 4 + 6 + 7 + 8 = 29

Input : A[] = {1, 5, 3, 8}
        B[] = {5, 1, 8, 3}
Output : 0
All elements are common.

Brute Force Method :
One simple approach is that for each element in A[] check whether it is present in B[], if it is present in then add it to the result. Similarly traverse B[] and for every element that is not present in B, add it to result.
Time Complexity: O(n^2).

Hashing concept :
Create an empty hash and insert elements of both arrays into it. Now traverse hash table and add all those elements whose count is 1. (As per the question, both arrays individually have distinct elements)

Below is the implementation of above approach:

// CPP program to find Non-overlapping sum
#include <bits/stdc++.h>
using namespace std;


// function for calculating
// Non-overlapping sum of two array
int findSum(int A[], int B[], int n)
{
    // Insert elements of both arrays
    unordered_map<int, int> hash;    
    for (int i = 0; i < n; i++) {
        hash[A[i]]++;
        hash[B[i]]++;
    }

    // calculate non-overlapped sum
    int sum = 0;
    for (auto x: hash) 
        if (x.second == 1)
            sum += x.first;
    
    return sum;
}

// driver code
int main()
{
    int A[] = { 5, 4, 9, 2, 3 };
    int B[] = { 2, 8, 7, 6, 3 };
    
    // size of array
    int n = sizeof(A) / sizeof(A[0]);

    // function call 
    cout << findSum(A, B, n); 
    return 0;
}

Output:

39

This article is contributed by ma5ter6it. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geekforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.