Problem
Design an algorithm to find all pairs of integers within an array which sum to a specified value.
Solution
We have found a pair of elements in an array which sum upto a given number already, this is a known problem called 2-sum problem. We know we can solve this problem in O(n) time.Let T be the sum.
Method 1 - Using Hash table solution
We can extend the same. We will add all the elements in the hash table. Now, for all elements we select element x, and check if hash table contains T-x and print it.
Method 2 - Sorting
- sort the array
- for each number in the array A(n), do a binary search to find the number A(x) such that A(n) + A(x) =T
0 comments:
Post a Comment