Friday, September 28, 2012

You are given an array of integers and a sum. Find all pairs of integers that equal that sum. Assume you have some sort of data structures that will be able to store the pairs. Write an algorithm to find all these pairs


Solution1
O(n^2) solution - Have two for loops

Solution2
Using a hashMap

Solution3
Most efficient - as no extra storage like hashMap

Sort the array

Two pointer - one to the begining and the other to the end of the array.

Compare the values pointed by the pointers untill the pointers collide
If the sum is lesser than m then increment the left pointer by one
If the sum is greater than m then decrement the right pointer by one
If the sum is equal to m then return "YES"


No comments:

Post a Comment