The Wayback Machine - https://web.archive.org/web/20240625104420/https://www.geeksforgeeks.org/two-pointers-technique/
Open In App

Two Pointers Technique

Last Updated : 14 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 naÃŊ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 Python, JavaScript, PHP etc and all Statically typed languages such as C++, Java, C# etc.

  1. NaÃŊve Approach using loops
  2. Optimal approach using two pointer algorithm

Method 1: NaÃŊve Approach 

Below is the implementation:

C++
// 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 code
int 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
// 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 1;

            // as the array is sorted
            if (A[i] + A[j] > X)
                break;
        }
    }

    // No pair found with given sum.
    return 0;
}

// Driver Code
int 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
// Java Program Illustrating Naive Approach to
// Find if There is a Pair in A[0..N-1] with Given Sum

// Importing all input output classes
import java.io.*;

// Main class
class 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
# 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 code
arr = [2, 3, 5, 8, 9, 10, 11]
val = 17

print(isPairSum(arr, len(arr), val))

# This code is contributed by maheshwaripiyush9
C#
// C# Program Illustrating Naive Approach to
// Find if There is a Pair in A[0..N-1] with Given Sum
using System;

// Main class
class 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
// 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>

Output
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. 

Below is the implementation:

C++
// 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(vector<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
    vector<int> arr = { 2, 3, 5, 8, 9, 10, 11 };

    // value to search
    int val = 17;

    // size of the array
    int arrSize = arr.size();

    // array should be sorted before using two-pointer
    // technique
    sort(arr.begin(), arr.end());

    // Function call
    cout << (isPairSum(arr, arrSize, val) ? "True"
                                          : "False");

    return 0;
}
Java
import java.util.Arrays;
import java.util.List;

public class PairSum {
    // 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(List<Integer> 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.get(i) + A.get(j) == X)
                return 1;

            // If sum of elements at current
            // pointers is less, we move towards
            // higher values by doing i++
            else if (A.get(i) + A.get(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
        List<Integer> arr
            = Arrays.asList(2, 3, 5, 8, 9, 10, 11);

        // value to search
        int val = 17;

        // size of the array
        int arrSize = arr.size();

        // array should be sorted before using the
        // two-pointer technique
        arr.sort(null);

        // Function call
        System.out.println(isPairSum(arr, arrSize, val)
                           != 0);
    }
}
Python
from typing import List


def isPairSum(A: List[int], N: int, X: int) -> bool:
    # 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++
        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--
        else:
            j -= 1

    return False


# Driver code
if __name__ == "__main__":
    # array declaration
    arr = [2, 3, 5, 8, 9, 10, 11]

    # value to search
    val = 17

    # size of the array
    arrSize = len(arr)

    # array should be sorted before using the two-pointer technique
    arr.sort()

    # Function call
    print(isPairSum(arr, arrSize, val))
C#
using System;
using System.Collections.Generic;

class PairSum {
    // Two pointer technique based solution to find
    // if there is a pair in A[0..N-1] with a given sum.
    static int IsPairSum(List<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
    static void Main(string[] args)
    {
        // array declaration
        List<int> arr
            = new List<int>{ 2, 3, 5, 8, 9, 10, 11 };

        // value to search
        int val = 17;

        // size of the array
        int arrSize = arr.Count;

        // array should be sorted before using the
        // two-pointer technique
        arr.Sort();

        // Function call
        Console.WriteLine(IsPairSum(arr, arrSize, val)
                          != 0);
    }
}
Javascript
function isPairSum(A, N, X) {
    // represents first pointer
    let i = 0;

    // represents second pointer
    let 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
const arr = [2, 3, 5, 8, 9, 10, 11];
const val = 17;
const arrSize = arr.length;

// array should be sorted before using the two-pointer technique
arr.sort((a, b) => a - b);

// Function call
console.log(isPairSum(arr, arrSize, val));

Output
True

Time Complexity:  O(n log n) (As sort function is used)
Auxiliary Space: O(1), since no extra space has been taken.

More problems based on two pointer technique. 



Next Article

Similar Reads

C++ Program for 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. C/C++ Code // Naive solution to find if th
4 min read
C Program for 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.   C/C++ Code // Naive solution to find if
3 min read
Python3 Program for 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. C/C++ Code # Naive solution to find if the
3 min read
Java Program for 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.   Java Code import java.io.*; class GFG {
4 min read
Javascript Program for 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.   C/C++ Code &lt;script&gt; // Naive solut
4 min read
Two-Pointer Technique in a Linked List
The two-pointer technique is a common technique used in linked list problems to solve a variety of problems efficiently. It involves using two pointers that traverse the linked list at different speeds or in different directions. Use Cases of Two-Pointer Technique in a Linked List:1. Finding the Middle of a Linked List:One common application of the
3 min read
C++ Program to compare two string using pointers
Given two strings, compare the strings using pointers Examples: Input: str1 = geeks, str2 = geeks Output: Both are equal Input: str1 = hello, str2 = hellu Output: Both are not equal As their length are same but characters are different The idea is to dereference given pointers, compare values and advance both of them. C/C++ Code // C++ Program to c
1 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
How to declare a Two Dimensional Array of pointers in C?
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creati
3 min read
Decrypt the encoded string with help of Matrix as per given encryption decryption technique
Given an encoded (or encrypted) string S of length N, an integer M. The task is to decrypt the encrypted string and print it. The encryption and decryption techniques are given as: Encryption: The original string is placed in a Matrix of M rows and N/M columns, such that the first character of the Original text or string is placed on the top-left c
6 min read
three90RightbarBannerImg