How do I calculate sum of sum of two integer arrays such that common elements are counted once?

83 Views Asked by At

Is there a constant time mathematical approach to calculate the sum of sum of two integer arrays such that the common numbers are counted only once?

For example, Sum of A1= {2,3} = 5 and

Sum of A2= {2,4} = 6

Can I have a mathematical equation to calculate the sum to be of 2+3+4 instead of counting 2 twice as 2+2+3+4?

Note: An efficient solution to the above problem would help solve the overall problem of finding pairwise intersections of a given list of subsets of an Universal set {1,2,3,4,....,n}

1

There are 1 best solutions below

7
On

I think you want to sum the union.

$$\sum_{x \in A \cup B} x$$

It can't be constant time as you need to check what are the elements.

Alternative approach:

$$\sum_{x\in A \cup B} x = \sum_{x\in A}x + \sum_{x \in B}x-\sum_{x \in A \cap B}x$$