Equal sum of two arrays

Equal sum of two arrays

Given tow arrays of integers, find a pair of values (one value from each array) that you can swap to give the two arrays the same sum.

Fact:

  • Suppose sum of array 1 is Sum1 and sum of array 2 is Sum2
  • then for a pair of element from each array x and y
  • Sum1 – x + y = Sum2 + x – y
  • i.e. Sum1 – Sum2 = 2x – 2y = 2(x-y)
  • i.e. x – y = (Sum1 – Sum2) / 2
  • So, the diff between both element is (Sum1 – Sum2) / 2
Algorithm:
  1.  Find sum (sum1) of array1
  2. Find sum (sum2) of array2
  3. Calculate target = (sum1 – sum2) / 2
  4. Convert array2 to set2
  5. Iterate array1 from start to end
    1. Compute complement = array1[i] – target
    2. Look up complement element in set (i.e array2)

Latest Source Code:
Github: SumSwap.java


Output:

Array1: [4, 1, 2, 1, 1, 2]
Array2: [3, 6, 3, 3]
Sum Swap : Result{element1=4, element2=6}
 
Author: Hrishikesh Mishra