Output:
1-20 19-10 -20 -30
A faster Algorithm O(n
2
lg n)
Instead of comparing elements in all three arrays, we can just compare elements in twoarrays and then sort the n
2
sums, and then we search for the additive inverse of any of thethird arrays’ element.In the example above we find the n
2
sums of the combinations from the first and the second arrays only (A and B). A=[1, -2, 16, -10, 5]; B=[-1, 4, 15, -20, 3]0, 5, 16, -19, 4, -3, 2, 13, -22, 1, 15, 20, 31, -4, 19, -11, -6, 5, -30, -7, 4, 9, 19, -15, 8Then we sort them in using merge sort, in O(lg n) time, and the result is:-30, -22, -19, -15, -11, -7, -6, -4, -3, 0, 1, 2, 4, 4, 5, 5, 8, 9, 13, 15, 16, 19, 19, 20, 31.Then we use binary search to search for the additive inverse of elements of the third array Cin the sorted list above. Each binary search will take lg (n
2
) time, we will perform n searches,and hence it will take 2nlg(n) time.C=[19, 30, -25, 12, -7] we search for -19, -30, 25, -12 and 7.-
30
, -22,
-19
, -15, -11, -7, -6, -4, -3, 0, 1, 2, 4, 4, 5, 5, 8, 9, 13, 15, 16, 19, 19, 20, 31.Total running time is O(n
2
)+O(lg n)+O(nlogn) ≈ O(n
2
lg n)
An even faster algorithm O(n
2
)
We can take this one step further, and instead of sorting the sums of the elements in thefirst two algorithms we place in an un-ordered fashion that will give us some leverage to find more information. Theoretically, we place them in a 2D array such that the values of the first array are in order and the values of the second array are in reverse order and then we fillthe array as follows:-10-21516155131620314-6259203-714819-1-11-30415-20-30-22-19-15-4We notice that the more to right and the more up the higher the sum, and vice versa (themore left and down the lower the sum). This will take us O(n
2
), because we still need to find the sum of all n
2
combinations.
Add a Comment