Sum Swap
16.21 Sum Swap: Given two 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.
Brute force very obvious: swap each possible combination, and compare the sums.
My optimized approach when as follows:
We know the a swap performs the following on the sum:
sumA - a + b
andsumB - b + a
We want to find the solution such that
sumA - a + b = sumB - b + a
. In other words, a swap that equates the sum.In the above example, we would obtain
a = -2 + b
andb = 2 + a
. Although both of which define the same relation, we apply both of these forumulas to our solution.Now it becomes possible for us to iterate through the arrays, and check for the values we expect given these relationships and the current values in the array. However, this is still order n^2 worst case.
I am not to sure if the following will be an improvement or not, but if we sort both arrays. We can iterate through both array in a smarter way. In particular, when an element exceeds the number we expect as the minimum (through the formulas), then we can move on to the next iteration of the for loop.
One flaw about this is that the solution return in index of the element of the sorted array, which would require some extra space to fix. This implies that it is not a very good solution.
Sorting is a subtle improvement, but not the best.
To optimize this even more, we can sort the elements of B into a hash map, with the value pair being its index we can reference later
Basically, we preform the same algorithm as above, besides the sorting; and simply iterate through A , and checking whether the appropriate value for B exists. This will take O(N).
Last updated