Two Pointers Technique
Last Updated :
29 Mar, 2024
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 C++, Java, Python, and even JavaScript
- Naïve Approach using loops
- Optimal approach using two pointer algorithm
Method 1: Naïve Approach
Below is the implementation:
C++
#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++) {
if (i == j)
continue ;
if (A[i] + A[j] == X)
return true ;
if (A[i] + A[j] > X)
break ;
}
}
return false ;
}
int main()
{
int arr[] = { 2, 3, 5, 8, 9, 10, 11 };
int val = 17;
int arrSize = *(&arr + 1) - arr;
sort(arr, arr + arrSize);
cout << isPairSum(arr, arrSize, val);
return 0;
}
|
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 1;
if (A[i] + A[j] > X)
break ;
}
}
return 0;
}
int main()
{
int arr[] = { 2, 3, 5, 8, 9, 10, 11 };
int val = 17;
int arrSize = sizeof (arr) / sizeof (arr[0]);
printf ( "%d" , isPairSum(arr, arrSize, val));
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 5 , 8 , 9 , 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 = i + 1 ; j < N; j++) {
if (i == j)
continue ;
if (A[i] + A[j] == X)
return 1 ;
if (A[i] + A[j] > X)
break ;
}
}
return 0 ;
}
}
|
Python3
def isPairSum(A, N, X):
for i in range (N):
for j in range (N):
if (i = = j):
continue
if (A[i] + A[j] = = X):
return True
if (A[i] + A[j] > X):
break
return 0
arr = [ 2 , 3 , 5 , 8 , 9 , 10 , 11 ]
val = 17
print (isPairSum(arr, len (arr), val))
|
C#
using System;
class GFG {
public static void Main(String[] args)
{
int [] arr = { 2, 3, 5, 8, 9, 10, 11 };
int val = 17;
Console.Write(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 = i + 1; j < N; j++) {
if (i == j)
continue ;
if (A[i] + A[j] == X)
return 1;
if (A[i] + A[j] > X)
break ;
}
}
return 0;
}
}
|
Javascript
<script>
function isPairSum(A, N, X)
{
for ( var i = 0; i < N-1; i++)
{
for ( var j = i+1; j < N; j++)
{
if (i == j)
continue ;
if (A[i] + A[j] == X)
return 1;
if (A[i] + A[j] > X)
break ;
}
}
return 0;
}
var arr=[ 2, 3, 5, 8, 9, 10, 11 ];
var val = 17;
var arrSize = 7;
document.write(isPairSum(arr, arrSize, val));
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
int isPairSum(vector< 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()
{
vector< int > arr = { 2, 3, 5, 8, 9, 10, 11 };
int val = 17;
int arrSize = arr.size();
sort(arr.begin(), arr.end());
cout << (isPairSum(arr, arrSize, val) ? "True"
: "False" );
return 0;
}
|
Java
import java.util.Arrays;
import java.util.List;
public class PairSum {
public static int isPairSum(List<Integer> A, int N,
int X)
{
int i = 0 ;
int j = N - 1 ;
while (i < j) {
if (A.get(i) + A.get(j) == X)
return 1 ;
else if (A.get(i) + A.get(j) < X)
i++;
else
j--;
}
return 0 ;
}
public static void main(String[] args)
{
List<Integer> arr
= Arrays.asList( 2 , 3 , 5 , 8 , 9 , 10 , 11 );
int val = 17 ;
int arrSize = arr.size();
arr.sort( null );
System.out.println(isPairSum(arr, arrSize, val)
!= 0 );
}
}
|
Python3
from typing import List
def isPairSum(A: List [ int ], N: int , X: int ) - > bool :
i = 0
j = N - 1
while i < j:
if A[i] + A[j] = = X:
return True
elif A[i] + A[j] < X:
i + = 1
else :
j - = 1
return False
if __name__ = = "__main__" :
arr = [ 2 , 3 , 5 , 8 , 9 , 10 , 11 ]
val = 17
arrSize = len (arr)
arr.sort()
print (isPairSum(arr, arrSize, val))
|
C#
using System;
using System.Collections.Generic;
class PairSum {
static int IsPairSum(List< 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;
}
static void Main( string [] args)
{
List< int > arr
= new List< int >{ 2, 3, 5, 8, 9, 10, 11 };
int val = 17;
int arrSize = arr.Count;
arr.Sort();
Console.WriteLine(IsPairSum(arr, arrSize, val)
!= 0);
}
}
|
Javascript
function isPairSum(A, N, X) {
let i = 0;
let j = N - 1;
while (i < j) {
if (A[i] + A[j] === X)
return true ;
else if (A[i] + A[j] < X)
i++;
else
j--;
}
return false ;
}
const arr = [2, 3, 5, 8, 9, 10, 11];
const val = 17;
const arrSize = arr.length;
arr.sort((a, b) => a - b);
console.log(isPairSum(arr, arrSize, val));
|
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...