-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathTwo_Pointers_Method.cpp
63 lines (53 loc) · 1.46 KB
/
Two_Pointers_Method.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
// Given a sorted array A, size of N ( N elements) and a target value X, find if there exists any pair of elements in the Array such that their total sum is equal to X.
/*
we can solve this by using Two pointers Method and thus time complexity will be O(N).
Two pointers Method is a method where one pointer starts from beginning and other from the end and they proceed towards each other simultaneously
*/
#include <bits/stdc++.h>
using namespace std;
int ar[100009];
bool Pair_exist_by_Two_Pointer_Method(int ar[], int N, int X)
{
int i = 0, j = N - 1, cur_sum = 0;
while(i < j)
{
cur_sum = ar[i] + ar[j];
if(cur_sum == X)
{
return true;
}
else if(cur_sum < X)
{
i++;
}
else if (cur_sum > X )
{
j--;
}
}
return false;
}
int main()
{
int N, X;
cout << "Input array size and target value\n";
cin >> N >> X;
for(int i = 0; i < N; i++)
{
cin >> ar[i];
}
bool solve = Pair_exist_by_Two_Pointer_Method(ar , N , X);
if(solve)
cout << "Pair found and their total sum is equal to target value\n";
else
cout << "Pair doesn't exist in the array\n";
}
/*
Standard Input and Output
Input array size and target value
6 70
10 20 35 50 75 80
Pair found and their total sum is equal to target value
Time Complexity : O(N)
Space Complexity : O(1)
*/