Two Pointers Technique

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.  

filter_none

edit
close

play_arrow

link
brightness_4
code

// Naive solution to find if there is a
// pair in A[0..N-1] with given sum.
#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 (A[i] + A[j] == X)
                return 1; // pair exists
 
            if (A[i] + A[j] > X)
                break; // as the array is sorted
        }
    }
 
    // No pair found with given sum.
    return 0;
}
 
// Driver Code
int main()
{
    int arr[]={3,5,9,2,8,10,11};
    int val=17;
    int arrSize = sizeof(arr)/sizeof(arr[0]);
   
    // Function call
    printf("%d",isPairSum(arr,arrSize,val));
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Naive solution to find if there is a
// pair in A[0..N-1] with given sum.
#include <iostream>
using namespace std;
 
bool isPairSum(int A[], int N, int X)
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (A[i] + A[j] == X)
                return true; // pair exists
 
            if (A[i] + A[j] > X)
                break; // as the array is sorted
        }
    }
 
    // No pair found with given sum.
    return false;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 5, 9, 2, 8, 10, 11 };
    int val = 17;
    int arrSize = *(&arr + 1) - arr;
   
    // Function call
    cout << isPairSum(arr, arrSize, val);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
        int arr[]={3,5,9,2,8,10,11};
        int val=17;
 
        System.out.println(isPairSum(arr,arr.length,val));
    }
  private static int isPairSum(int A[],int  N,int X){
     for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (A[i] + A[j] == X)
                return 1; // pair exists
 
            if (A[i] + A[j] > X)
                break; // as the array is sorted
        }
    }
 
    // No pair found with given sum.
    return 0;
  }
}
chevron_right

Output
1

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. 



filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
 
// 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[] = { 3, 5, 9, 2, 8, 10, 11 };
     
    // value to search
    int val = 17;
     
    // size of the array
    int arrSize = sizeof(arr) / sizeof(arr[0]);
   
    // Function call
    printf("%d", isPairSum(arr, arrSize, val));
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
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[] = { 3, 5, 9, 2, 8, 10, 11 };
     
    // value to search
    int val = 17;
     
    // size of the array
    int arrSize = *(&arr + 1) - arr;
     
    // Function call
    cout << (bool)isPairSum(arr, arrSize, val);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.io.*;
 
class GFG
{
     // Two pointer technique based solution to find
    // if there is a pair in A[0..N-1] with a given sum.
    public static 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
    public static void main(String[] args)
    {
        // array declaration
        int arr[] = { 3, 5, 9, 2, 8, 10, 11 };
         
        // value to search
        int val = 17;
       
        // size of the array
        int arrSize = arr.length;
       
        // Function call
        System.out.println(isPairSum(arr, arrSize, val));
    }
}
chevron_right

Output
1

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. 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




This article is contributed by Rohan Das. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AkshdeepRAJAWAT, raviteja2110

Article Tags :