# Find Pair with given Sum in the Array

Given an unsorted array of integers, find a pair with given sum in it.

For example,

Input:

arr = [8, 7, 2, 5, 3, 1]
sum = 10

Output:

Pair found at index 0 and 2 (8 + 2)
or
Pair found at index 1 and 4 (7 + 3)

### 1. Naive Approach –

Naive solution would be to consider every pair in given array and return if desired sum is found.

## Java

Output:

Pair found at index 0 and 2

The time complexity of above solution is O(n2) and auxiliary space used by the program is O(1).

### 2. O(nlog(n)) solution using Sorting –

The idea is to sort the given array in ascending order and maintain search space by maintaining two indices (low and high) that initially points to two end-points of the array. Then we loop till low is less than high index and reduce search space arr[low..high] at each iteration of the loop. We compare sum of elements present at index low and high with desired sum and increment low if sum is less than the desired sum else we decrement high is sum is more than the desired sum. Finally, we return if pair found in the array.

## Java

Output:

Pair found

The time complexity of above solution is O(nlogn) and auxiliary space used by the program is O(1).

### 3. O(n) solution using Hashing –

We can use map to easily solve this problem in linear time. The idea is to insert each element of the array arr[i] in a map. We also checks if difference (arr[i], sum-arr[i]) already exists in the map or not. If the difference is seen before, we print the pair and return.

## Java

Output:

Pair found at index 0 and 2

The time complexity of above solution is O(n) and auxiliary space used by the program is O(n).

Exercise:

1. Extend the solution to print all pairs in the array having given sum.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Subscribe
Notify of
Guest
arandomguy

I disabled adblock on this site. The ads on this site are not at all annoying, and this is the least I can do to support the team of techiedelight. You are doing a great job. Keep at it.

Guest
Rimpa

Please keep up the good work. The list of problems are really appreciable. And it is easy to understand. I am going to recommend this site to my friends. Please add more problems. Please!

Guest
AllergicToBitches

Awesome post..

Guest
anonymous

It’s worth noting that hash table operations are O(1) on average, but O(n) in the worst case. So in the worst case, the complexity of the hash based solution is O(n^2). In practice of course, if your hash function isn’t terrible, this is still probably the fastest solution of the three.

Guest
vitaly

One note though, is that the Map solution does not take into account any duplicate values.

Guest

actually it does. if you have a list {6, 10, 2, 5, 5, 3, 1}
the map you make would look like this:
[0, (10 – 6) = 4]
[1, (10 – 10) = 0]
[2, (10 – 2) = 8]
[3, (10 – 5) = 5]
[4, (10 – 5) = 5] ———> at this point it would look for a 5 in the map created so far. It would find that there is a 5 at index 3. Therefore, it would report index 3 and index 4 which is the correct output.

Guest
yo bruh!

{8, 7, 2, 2, 3, 1} !?

Guest
glib

Here are are the last two algorithms in C (using glib for the 3rd one): https://ideone.com/1PHYH3

Guest
vc723

last algo doesnt account for the index

Guest
suvro

isPairPresent : http://ideone.com/IyXytR

Guest
holod

In all of the code samples here, you return after the first pair is found, without checking for any other pairs out there. This way you skip the second pair in a give input.

Guest
mepler

In the hashing solution, what is the purpose of storing the index of the current element in the Map (line 26 in Java)?

Guest

how third solution is o(n)?
searching in map is not always o(1).

Guest
Vainglory

Hash table complexity analysis is usually done on the average case, which is O(1) including collisions. Worst case O(n) practically never happens for any dependable hash table implementation like std::unordered_map in C++ and HashMap in Java. It is safe to go with O(1) as hash lookups has O(1) access with high probability. But if you’re using std::map or TreeMap (which are implemented using a tree), then it is a whole different story.

Guest
NeelLohit

Thank you for the solutions. I just have one question. Given the fact that the sorting is done outside the loop for the second solution, is O(nlogn) the correct time complexity?

Guest
vc723

i have a question. how would this handle a repeated number that is a pair? say 5,5 for 10 with first 5 at index 1 and second 5 at index 6?

Guest
Rnet

I know the post didn’t cover this in javascript, but I ran all three of these in JS and also tested the time for the functions to run at a large scale, and the first answer was much faster.

The results of 2nd and 3rd are nearly the same. I guess JS Maps are not nearly as good as JAVA maps. Here are the JAVA results just in case you are wondering using a micro timer method.

/* results
findPair(): 6048539276 ns
findPairTwo(): 5277386525 ns
findPairThree(): 4845864175 ns
*/
And the code on GitHub in case you need to see it for some reason… https://github.com/BrianARuff/pairWithSumInArray-JAVA

Guest
Sundeep Y

has any one tried getting all the pairs in the given array ?

Guest
Akhil Aggarwal

Hi,
Do you know 2nd method of yours won’t work if there are duplicate elements in array or if all the elements in the array are same,then there would be certain value of permutations which should be taken care of.You need to have some provision for that

Guest
Ankit

Code works fine. Did you ran the code? Do you have any input on which it fails?