Given an integer array, find pairs in an array which sum up to a given number.
For example: Array{4,5,1,3,2} and required sum=6 then output should be [1,5] and [2,4].
Solution:
1. O(n)/O(n):
Put all items to a hashtable, and then iterate over the array once more and check if the hashtable contains (sum-a[i]). Print the pair if so.
2. O(n log n)/O(1)
Sort the array and start pointers from both ends of the array checking if the given pair add up to the given value.
- If the current pair sum equals the value of the given number print the pair.
- If the current pair sum exceeds the given number decrement the right pointer by 1
- else increment the left pointer by 1
Complexity:
time - O(n) or O(n log n)Links and credits:
space - O(n) or O(1)
http://www.careercup.com/question?id=19682725
No comments:
Post a Comment