Two Pointers Technique

Difficulty Level :
Easy
Two pointers is really an easy and effective technique that 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.
Illustration : 
A[] = {10, 20, 35, 50, 75, 80}
X = =70
i = 0
j = 5

A[i] + A[j] = 10 + 80 = 90
Since A[i] + A[j] > X, j--
i = 0
j = 4

A[i] + A[j] = 10 + 75 = 85
Since A[i] + A[j] > X, j--
i = 0
j = 3

A[i] + A[j] = 10 + 50 = 60
Since A[i] + A[j] < X, i++
i = 1
j = 3
m
A[i] + A[j] = 20 + 50 = 70
Thus this signifies that Pair is Found.
Let us do discuss the working of two pointer algorithm in brief which is as follows. 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.
Methods:
Here we will be proposing a two-pointer algorithm by starting off with the naïve approach only in order to showcase the execution of operations going on in both methods and secondary to justify how two-pointer algorithm optimizes code via time complexities across all dynamic programming languages such as C+, Java, Python, and even JavaScript
Naïve Approach using loopsOptimal approach using two pointer algorithm
Naïve Approach using loops
Optimal approach using two pointer algorithm
Implementation:
Method 1: Naïve Approach 
Examples 
C++
C
Java
Python3
C#
Javascript
// C++ Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum  // Importing all libraries#include <bits/stdc++.h>  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++) {            // as equal i and j means same element            if (i == j)                continue;              // pair exists            if (A[i] + A[j] == X)                return true;              // as the array is sorted            if (A[i] + A[j] > X)                break;        }    }      // No pair found with given sum.    return false;}  // Driver codeint main(){    int arr[] = { 2, 3, 5, 8, 9, 10, 11 };    int val = 17;    int arrSize = *(&arr + 1) - arr;    sort(arr, arr + arrSize); // Sort the array    // Function call    cout << isPairSum(arr, arrSize, val);      return 0;}
// C Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum  // Importing all libraries#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++) {            // as equal i and j means same element            if (i == j)                continue;              // pair exists            if (A[i] + A[j] == X)                return true;              // as the array is sorted            if (A[i] + A[j] > X)                break;        }    }      // No pair found with given sum.    return 0;}  // Driver Codeint main(){    int arr[] = { 2, 3, 5, 8, 9, 10, 11 };    int val = 17;    int arrSize = sizeof(arr) / sizeof(arr[0]);      // Function call    printf("%d", isPairSum(arr, arrSize, val));      return 0;}
// Java Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum  // Importing all input output classesimport java.io.*;  // Main classclass GFG {      // Method 1    // Main driver method    public static void main(String[] args)    {        // Declaring and initializing array        int arr[] = { 2, 3, 5, 8, 9, 10, 11 };          int val = 17;          System.out.println(isPairSum(arr, arr.length, val));    }      // Method 2    //  To find Pairs in A[0..N-1] with given sum    private static int isPairSum(int A[], int N, int X)    {        // Nested for loops for iterations        for (int i = 0; i < N; i++) {            for (int j = i + 1; j < N; j++) {                // As equal i and j means same element                if (i == j)                      // continue keyword skips the execution                    // for following condition                    continue;                  // Condition check if pair exists                if (A[i] + A[j] == X)                    return 1;                  // By now the array is sorted                if (A[i] + A[j] > X)                      // Break keyword to hault the execution                    break;            }        }          // No pair found with given sum.        return 0;    }}
# Python Program Illustrating Naive Approach to# Find if There is a Pair in A[0..N-1] with Given Sum  # Method    def isPairSum(A, N, X):      for i in range(N):        for j in range(N):              # as equal i and j means same element            if(i == j):                continue              # pair exists            if (A[i] + A[j] == X):                return True              # as the array is sorted            if (A[i] + A[j] > X):                break      # No pair found with given sum    return 0    # Driver codearr = [2, 3, 5, 8, 9, 10, 11]val = 17  print(isPairSum(arr, len(arr), val))  # This code is contributed by maheshwaripiyush9
// C# Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sumusing System;  // Main classclass GFG {      // Method 1    // Main driver method    public static void Main(String[] args)    {          // Declaring and initializing array        int[] arr = { 2, 3, 5, 8, 9, 10, 11 };          int val = 17;          Console.Write(isPairSum(arr, arr.Length, val));    }      // Method 2    //  To find Pairs in A[0..N-1] with given sum    private static int isPairSum(int[] A, int N, int X)    {          // Nested for loops for iterations        for (int i = 0; i < N; i++) {            for (int j = i + 1; j < N; j++) {                  // As equal i and j means same element                if (i == j)                      // continue keyword skips the execution                    // for following condition                    continue;                  // Condition check if pair exists                if (A[i] + A[j] == X)                    return 1;                  // By now the array is sorted                if (A[i] + A[j] > X)                      // Break keyword to hault the execution                    break;            }        }          // No pair found with given sum.        return 0;    }}  // This code is contributed by shivanisinghss2110
// JavaScript Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum  <script>   // Naive solution to find if there is a// pair in A[0..N-1] with given sum.  function isPairSum(A, N, X){        for (var i = 0; i < N-1; i++)        {            for (var j = i+1; j < N; j++)            {                // as equal i and j means same element                if (i == j)                    continue;                  // pair exists                if (A[i] + A[j] == X)                    return 1;                  // as the array is sorted                if (A[i] + A[j] > X)                    break;            }        }          // No pair found with given sum.        return 0;}                  var arr=[ 2, 3, 5, 8, 9, 10, 11 ];                  // value to search        var val = 17;              // size of the array        var arrSize = 7;              // Function call        document.write(isPairSum(arr, arrSize, val));  </script>
1
Time Complexity:  O(n2).
Auxiliary Space: O(1)
Method 2: Two Pointers Technique
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. 
Examples
C++
C
Java
Python3
C#
Javascript
// 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 <iostream>#include <algorithm>  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 codeint 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    cout << (bool)isPairSum(arr, arrSize, val);      return 0;}
// 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 I/O libraries #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;}  // Main method int main(){    // Array declaration    int arr[] = { 2, 3, 5, 8, 9, 10, 11 };          // Custom value to be searched    int val = 17;          // size of the array    int arrSize = sizeof(arr) / sizeof(arr[0]);        // Function call    printf("%d", isPairSum(arr, arrSize, val));      return 0;}
// Java Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique  // Importing all utility classesimport java.io.*;  // Main classclass 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[] = { 2, 3, 5, 8, 9, 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));    }}
# Python Program Illustrating Naive Approach to# Find if There is a Pair in A[0..N-1] with Given Sum# Using Two-pointers Technique  # Method def isPairSum(A, N, X):      # represents first pointer    i = 0      # represents second pointer    j = N - 1      while(i < j):                # If we find a pair        if (A[i] + A[j] == X):            return True          # If sum of elements at current        # pointers is less, we move towards        # higher values by doing i += 1        elif(A[i] + A[j] < X):            i += 1          # If sum of elements at current        # pointers is more, we move towards        # lower values by doing j -= 1        else:            j -= 1    return 0  # array declarationarr = [2, 3, 5, 8, 9, 10, 11]  # value to searchval = 17  print(isPairSum(arr, len(arr), val))  # This code is contributed by maheshwaripiyush9.
// 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 all utility classesusing System;  // Main classclass 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 = { 2, 3, 5, 8, 9, 10, 11 };                  // value to search        int val = 17;                // size of the array        int arrSize = arr.Length;                // Function call        Console.Write(isPairSum(arr, arrSize, val));    }}  // This code is contributed by shivanisinghss2110
// JavaScript Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique  <script>// Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.function isPairSum(A, N, X){      // represents first pointer    var i = 0;      // represents second pointer    var j = N - 1;      while (i < j) {          // If we find a pair        if (A[i] + A[j] == X)            return true;          // 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 false;}  // Driver code      // array declaration    var arr = [ 2, 3, 5, 8, 9, 10, 11 ];          // value to search    var val = 17;          // size of the array    var arrSize =7;          // Function call    document.write(isPairSum(arr, arrSize, val));          // This Code is Contributed by Harshit Srivastava     </script>
1
Time Complexity:  O(n log n) (As sort function is used)
Auxiliary Space: O(1)
More problems based on two pointer technique. 
Find the closest pair from two sorted arrays
Find the pair in array whose sum is closest to x
Find all triplets with zero sum
Find a triplet that sum to a given value
Find a triplet such that sum of two equals to third element
Find four elements that sum to a given value
AkshdeepRAJAWAT
raviteja2110
homer_simpson
maheswaripiyush9
srivastavaharshit848
akshitsaxenaa09
roshsoftdev
simmytarika5
souravseal99
shivanisinghss2110
sriramprasanth19
haishand
abdirahmanahmed49
sagartomar9927
sarrransh
aviralsheoran2002
codewithmini
two-pointer-algorithm
Arrays
Searching
Technical Scripter
two-pointer-algorithm
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number