-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_FindPairGivenDifference.cpp
70 lines (49 loc) · 1.27 KB
/
GFG_FindPairGivenDifference.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
https://practice.geeksforgeeks.org/problems/find-pair-given-difference1559/1#
Find Pair Given Difference
*/
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
bool findPair(int arr[], int size, int n);
int main()
{
int t;
cin>>t;
while(t--)
{
int l,n;
cin>>l>>n;
int arr[l];
for(int i=0;i<l;i++)
cin>>arr[i];
if(findPair(arr, l, n))
cout<<1<<endl;
else cout<<"-1"<<endl;
}
return 0;
}// } Driver Code Ends
bool findPair(int arr[], int size, int n){
unordered_map<int,int> um;
for(int i=0; i<size; i++)
{
if(um.find(arr[i]+n) != um.end()) return true;
if(um.find(arr[i]-n) != um.end()) return true;
um.insert({arr[i], i});
}
return false;
}
bool findPair_(int arr[], int size, int n){
sort(arr, arr+size);
int i=0, j=1, diff=0; //there is monotonicity that we are moving in only one direction in order to determine the answer.
while(i<size && j<size)
{
if(i==j) j++;
diff = arr[j]-arr[i];
if(diff == n) return true;
else if(diff > n) i++; //decrease the diff
else
j++;
}
return false;
}