C Program for Two Pointers Technique
Last Updated :
13 Jan, 2022
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.
Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X.
Let’s see the naive solution. Â
C
#include <stdio.h>
int isPairSum( int A[], int N, int X)
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++)
{
if (i == j)
continue ;
if (A[i] + A[j] == X)
return true ;
if (A[i] + A[j] > X)
break ;
}
}
return 0;
}
int main()
{
int arr[]={3,5,9,2,8,10,11};
int val=17;
int arrSize = sizeof (arr)/ sizeof (arr[0]);
printf ( "%d" ,isPairSum(arr,arrSize,val));
return 0;
}
|
Time Complexity: Â O(n2).
Now let’s see how the two-pointer technique works. We take two pointers, one representing the first element and other representing the last element of the array, and then we add the values kept at both the pointers. If their sum is smaller than X then we shift the left pointer to right or if their sum is greater than X then we shift the right pointer to left, in order to get closer to the sum. We keep moving the pointers until we get the sum as X.Â
C
#include <stdio.h>
int isPairSum( int A[], int N, int X)
{
int i = 0;
int j = N - 1;
while (i < j)
{
if (A[i] + A[j] == X)
return 1;
else if (A[i] + A[j] < X)
i++;
else
j--;
}
return 0;
}
int main()
{
int arr[] = { 3, 5, 9, 2, 8, 10, 11 };
int val = 17;
int arrSize = sizeof (arr) / sizeof (arr[0]);
printf ( "%d" , isPairSum(arr, arrSize, val));
return 0;
}
|
Illustration :Â
Â
Time Complexity: Â O(n)
How does this work?Â
The algorithm basically uses the fact that the input array is sorted. We start the sum of extreme values (smallest and largest) and conditionally move both pointers. We move left pointer i when the sum of A[i] and A[j] is less than X. We do not miss any pair because the sum is already smaller than X. Same logic applies for right pointer j.
More problems based on two pointer technique.Â
Please refer complete article on Two Pointers Technique for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...