Nonoverlapping sum of two sets (original) (raw)

Non-overlapping sum of two sets

Last Updated : 23 Oct, 2024

Given two arrays A[] and B[] of size n. It is given that both array individually contains distinct elements. We need to find the 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(n2).
**Auxiliary Space: O(1), As constant extra space is used.

**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 the above approach:

C++ `

// 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;

}

Java

// Java program to find Non-overlapping sum import java.io.; import java.util.;

class GFG {

// function for calculating 
// Non-overlapping sum of two array 
static int findSum(int[] A, int[] B, int n)
{
    // Insert elements of both arrays
    HashMap<Integer, Integer> hash = new HashMap<>();
    for (int i = 0; i < n; i++)
    {
        if (hash.containsKey(A[i]))
            hash.put(A[i], 1 + hash.get(A[i]));
        else
            hash.put(A[i], 1);

        if (hash.containsKey(B[i]))
            hash.put(B[i], 1 + hash.get(B[i]));
        else
            hash.put(B[i], 1);
    }

    // calculate non-overlapped sum 
    int sum = 0;
    for (Map.Entry entry : hash.entrySet())
    {
        if (Integer.parseInt((entry.getValue()).toString()) == 1)
            sum += Integer.parseInt((entry.getKey()).toString());
    }

    return sum;

}

// Driver code
public static void main(String args[])
{
    int[] A = { 5, 4, 9, 2, 3 }; 
    int[] B = { 2, 8, 7, 6, 3 }; 

    // size of array 
    int n = A.length;

    // function call 
    System.out.println(findSum(A, B, n));
}

}

// This code is contributed by rachana soma

Python3

Python3 program to find Non-overlapping sum

from collections import defaultdict

Function for calculating

Non-overlapping sum of two array

def findSum(A, B, n):

# Insert elements of both arrays 
Hash = defaultdict(lambda:0)
for i in range(0, n): 
    Hash[A[i]] += 1
    Hash[B[i]] += 1

# calculate non-overlapped sum 
Sum = 0
for x in Hash: 
    if Hash[x] == 1: 
        Sum += x 

return Sum

Driver code

if name == "main":

A = [5, 4, 9, 2, 3] 
B = [2, 8, 7, 6, 3] 

# size of array 
n = len(A) 

# Function call 
print(findSum(A, B, n)) 

This code is contributed

by Rituraj Jain

C#

// C# program to find Non-overlapping sum using System; using System.Collections.Generic;

class GFG {

// function for calculating 
// Non-overlapping sum of two array 
static int findSum(int[] A, int[] B, int n)
{
    // Insert elements of both arrays
    Dictionary<int, int> hash = new Dictionary<int, int>();
    for (int i = 0; i < n; i++)
    {
        if (hash.ContainsKey(A[i]))
        {
            var v = hash[A[i]];
            hash.Remove(A[i]);
            hash.Add(A[i], 1 + v);
        }
        else
            hash.Add(A[i], 1);

        if (hash.ContainsKey(B[i]))
        {
            var v = hash[B[i]];
            hash.Remove(B[i]);
            hash.Add(B[i], 1 + v);
        }
        else
            hash.Add(B[i], 1);
    }

    // calculate non-overlapped sum 
    int sum = 0;
    foreach(KeyValuePair<int, int> entry in hash)
    {
        if ((entry.Value) == 1)
            sum += entry.Key;
    }

    return sum;

}

// Driver code
public static void Main(String []args)
{
    int[] A = { 5, 4, 9, 2, 3 }; 
    int[] B = { 2, 8, 7, 6, 3 }; 

    // size of array 
    int n = A.Length;

    // function call 
    Console.WriteLine(findSum(A, B, n));
}

}

// This code is contributed by 29AjayKumar

JavaScript

`

**Time Complexity: O(n), since inserting in an unordered map is amortized constant.
**Auxiliary Space: O(n).

**Another method: Using set data structure

Below is the implementation of the above approach:

C++ `

// 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) { int sum = 0;

// Insert elements of Array A in set
// and add into sum
set<int> st;
for (int i = 0; i < n; i++) {
    st.insert(A[i]);
    sum += A[i];
}

// Check if B's element are there in set
// if exist then remove current element from
// set, otherwise add current element into sum
for (int i = 0; i < n; i++) {
    if (st.find(B[i]) == st.end()) {
        sum += B[i];
    }
    else {
        sum -= B[i];
    }
}

// Finally, return sum
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;

}

// This code is contributed by hkdass001

Java

// Java program to find Non-overlapping sum

import java.io.; import java.util.;

class GFG {

  // function for calculating
// Non-overlapping sum of two array
public static int findSum(int[] A, int[] B, int n) {
    int sum = 0;

    // Insert elements of Array A in set
    // and add into sum
    Set<Integer> st = new HashSet<>();
    for (int i = 0; i < n; i++) {
        st.add(A[i]);
        sum += A[i];
    }

    // Check if B's element are there in set
    // if exist then remove current element from
    // set, otherwise add current element into sum
    for (int i = 0; i < n; i++) {
        if (!st.contains(B[i])) {
            sum += B[i];
        }
        else {
            sum -= B[i];
        }
    }

    // Finally, return sum
    return sum;
}

public static void main (String[] args) {
    int[] A = { 5, 4, 9, 2, 3 };
    int[] B = { 2, 8, 7, 6, 3 };

    // size of array
    int n = A.length;

    // function call
    System.out.println(findSum(A, B, n));
}

}

// This code is contributed by lokesh.

Python

python program to find Non-overlapping sum

function for calculating

Non-overlapping sum of two array

def findSum(A, B, n): sum = 0;

# Insert elements of Array A in set
# and add into sum
st = set();
for i in range(0,n): 
    st.add(A[i]);
    sum += A[i];

# Check if B's element are there in set
# if exist then remove current element from
# set, otherwise add current element into sum
for i in range (0, n):
    if (B[i] in st):
        sum -= B[i];
    else :
        sum += B[i];

# Finally, return sum
return sum;

Driver code

A = [ 5, 4, 9, 2, 3 ]; B = [ 2, 8, 7, 6, 3 ];

size of array

n = len(A);

function call

print(findSum(A, B, n));

C#

// C# code for the above approach

using System; using System.Collections.Generic;

public class GFG {

// function for calculating
// Non-overlapping sum of two array
public static int FindSum(int[] A, int[] B, int n)
{
    int sum = 0;

    // Insert elements of Array A in set
    // and add into sum
    HashSet<int> st = new HashSet<int>();
    for (int i = 0; i < n; i++) {
        st.Add(A[i]);
        sum += A[i];
    }

    // Check if B's element are there in set
    // if exist then remove current element from
    // set, otherwise add current element into sum
    for (int i = 0; i < n; i++) {
        if (!st.Contains(B[i])) {
            sum += B[i];
        }
        else {
            sum -= B[i];
        }
    }

    // Finally, return sum
    return sum;
}

static public void Main()
{

    // Code
    int[] A = { 5, 4, 9, 2, 3 };
    int[] B = { 2, 8, 7, 6, 3 };

    // size of array
    int n = A.Length;

    // function call
    Console.WriteLine(FindSum(A, B, n));
}

}

// This code is contributed by lokeshmvs21.

JavaScript

// Javascript program to find Non-overlapping sum

// function for calculating // Non-overlapping sum of two array function findSum(A, B, n) { let sum = 0;

// Insert elements of Array A in set
// and add into sum
let st = new Set();
for (let i = 0; i < n; i++) {
    st.add(A[i]);
    sum += A[i];
}

// Check if B's element are there in set
// if exist then remove current element from
// set, otherwise add current element into sum
for (let i = 0; i < n; i++) {
    if (!st.has(B[i])) {
        sum += B[i];
    }
    else {
        sum -= B[i];
    }
}

// Finally, return sum
return sum;

}

// Driver code let A = [ 5, 4, 9, 2, 3 ]; let B = [ 2, 8, 7, 6, 3 ];

// size of array
let n = A.length;

// function call
document.write(findSum(A, B, n));

`

**Time Complexity: O(n*log n)
**Auxiliary Space: O(n)