forked from AaqilSh/DSA-Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_pointer_technique.cpp
More file actions
67 lines (53 loc) · 1.45 KB
/
two_pointer_technique.cpp
File metadata and controls
67 lines (53 loc) · 1.45 KB
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
// C++ Program Illustrating Naive Approach to
// Find if There is a Pair in A[0..N-1] with Given Sum
// Using Two-pointers Technique
// Importing required libraries
#include <bits/stdc++.h>
using namespace std;
// Two pointer technique based solution to find
// if there is a pair in A[0..N-1] with a given sum.
int isPairSum(int A[], int N, int X)
{
// represents first pointer
int i = 0;
// represents second pointer
int j = N - 1;
while (i < j) {
// If we find a pair
if (A[i] + A[j] == X)
return 1;
// If sum of elements at current
// pointers is less, we move towards
// higher values by doing i++
else if (A[i] + A[j] < X)
i++;
// If sum of elements at current
// pointers is more, we move towards
// lower values by doing j--
else
j--;
}
return 0;
}
// Driver code
int main()
{
// array declaration
int arr[] = { 2, 3, 5, 8, 9, 10, 11 };
// value to search
int val = 17;
// size of the array
int arrSize = *(&arr + 1) - arr;
// array should be sorted before using two-pointer technique
sort(arr, arr+7);
// Function call
if((bool)isPairSum(arr, arrSize, val)==1)
{
cout<<"Valid Pair present";
}
else
{
cout<<"No Valid Pair found";
}
return 0;
}