Find a pair with the given difference

Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n.

Examples:
Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78
Output: Pair Found: (2, 80)

Input: arr[] = {90, 70, 20, 80, 50}, n = 45

Output: No Such Pair

C++:
01 bool pairFinder(int A[], int size, int d, int& a, int& b)
02 {
03     set <int> s;
04     for(int i=0;i<size;i++){
05         s.insert(A[i]+d);
06     }
07     for(int i=0;i<size;i++){
08         if(s.find(A[i])!=s.end()){
09             a=A[i]d;
10             b=A[i];
11             return true;
12         }
13     }
14     return false;
15 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s