Pairs with Sum
16.24 Pairs with Sum: Design an algorithm to find all pairs of integers within an array which sum to a specified value.
Brute force: Check every possible combinational pair and see if it matches the sum. O(n^2)
Better:
If we sort the pairs (O(nlogn)), then we can try to map each pair with every other possible pair like before, except this time we can break out of the for loop when we know that the next iteration will exceed the number we expect. We also know when to break out of the loop entirely (when we exceed the value in the outer for loop). Along in the process, we can check for duplicates - and move onto the next iteration. And finally, we can also break out when we get a successful match. This is because we know that there is only a single unique solution per some value in the array A. After a successful match, every after is guarenteed either to not happen, or result in a duplicate pair.
Even Better:
Use a hash table to check for the value you expect for the sum. O(N) time complexity, O(N) extra space.
Current flaws: outputs pairs that are essentially redundent. e.g. (2,3) will also output (3,2) its inverse. Depending on the specificity of the problem, I may have to change this. A solution to this may be to use a map, instead of an unordered map, and tell it to look for values beyond a particular interval.
Last updated