Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Java Program for Two Pointers Technique
Next article icon

Two Pointers Technique

Last Updated : 16 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists any pair of elements (arr[i], arr[j]) such that their sum is equal to the target.

Illustration : 

Input: arr[] = {10, 20, 35, 50}, target =70
Output: Yes
Explanation : There is a pair (20, 50) with given target.

Input: arr[] = {10, 20, 30}, target =70
Output : No
Explanation : There is no pair with sum 70

Input: arr[] = {-8, 1, 4, 6, 10, 45], target = 16
Output: Yes
Explanation : There is a pair (6, 10) with given target.

Table of Content

  • Naive Method - O(n^2) Time and O(1) Space
  • Two-Pointer Technique - O(n) time and O(1) space
  • How does this work?
  • More problems based on two pointer technique. 

Naive Method - O(n^2) Time and O(1) Space

The very basic approach is to generate all the possible pairs and check if any of them add up to the target value. To generate all pairs, we simply run two nested loops.

C++
#include <bits/stdc++.h> using namespace std;  bool twoSum(vector<int> &arr, int target) {     int n = arr.size();      // Consider all pairs (arr[i], arr[j])     for (int i = 0; i < n; i++) {         for (int j = i + 1; j < n; j++) {                        // Check if the sum of the current pair             // equals the target             if (arr[i] + arr[j] == target) {                 return true;             }         }     }        // If no pair is found after checking all      return false; }  int main() {       vector<int> arr = {0, -1, 2, -3, 1};     int target = -2;     cout << ((twoSum(arr, target))? "true" : "false");     return 0; } 
C
#include <stdbool.h> #include <stdio.h>  // Function to check whether any pair exists // whose sum is equal to the given target value bool twoSum(int arr[], int n, int target){      // Iterate through each element in the array     for (int i = 0; i < n; i++){          // For each element arr[i], check every         // other element arr[j] that comes after it         for (int j = i + 1; j < n; j++){              // Check if the sum of the current pair             // equals the target             if (arr[i] + arr[j] == target)                 return true;         }     }     // If no pair is found after checking     // all possibilities     return false; }  int main(){      int arr[] = {0, -1, 2, -3, 1};     int target = -2;     int n = sizeof(arr) / sizeof(arr[0]);      // Call the twoSum function and print the result     if (twoSum(arr, n, target))         printf("true\n");     else         printf("false\n");        return 0; } 
Java
class GfG {      // Function to check whether any pair exists     // whose sum is equal to the given target value     static boolean twoSum(int[] arr, int target){         int n = arr.length;          // Iterate through each element in the array         for (int i = 0; i < n; i++) {             // For each element arr[i], check every             // other element arr[j] that comes after it             for (int j = i + 1; j < n; j++) {                 // Check if the sum of the current pair                 // equals the target                 if (arr[i] + arr[j] == target) {                     return true;                 }             }         }         // If no pair is found after checking         // all possibilities         return false;     }      public static void main(String[] args){          int[] arr = { 0, -1, 2, -3, 1 };         int target = -2;          // Call the twoSum function and print the result         if (twoSum(arr, target))             System.out.println("true");         else             System.out.println("false");     } } 
Python
# Function to check whether any pair exists # whose sum is equal to the given target value def two_sum(arr, target):     n = len(arr)      # Iterate through each element in the array     for i in range(n):                # For each element arr[i], check every         # other element arr[j] that comes after it         for j in range(i + 1, n):                        # Check if the sum of the current pair             # equals the target             if arr[i] + arr[j] == target:                 return True                    # If no pair is found after checking     # all possibilities     return False  arr = [0, -1, 2, -3, 1] target = -2  # Call the two_sum function and print the result if two_sum(arr, target):     print("true") else:     print("false") 
C#
using System;  class GfG {      // Function to check whether any pair exists     // whose sum is equal to the given target value     static bool TwoSum(int[] arr, int target) {         int n = arr.Length;          // Iterate through each element in the array         for (int i = 0; i < n; i++) {                        // For each element arr[i], check every             // other element arr[j] that comes after it             for (int j = i + 1; j < n; j++) {                                // Check if the sum of the current pair                 // equals the target                 if (arr[i] + arr[j] == target) {                     return true;                 }             }         }             // If no pair is found after checking         // all possibilities         return false;     }      static void Main() {                int[] arr = { 0, -1, 2, -3, 1 };         int target = -2;          // Call the TwoSum function and print the result         if (TwoSum(arr, target))           Console.WriteLine("true");         else            Console.WriteLine("false");     } } 
JavaScript
// Function to check whether any pair exists // whose sum is equal to the given target value function twoSum(arr, target) {     let n = arr.length;      // Iterate through each element in the array     for (let i = 0; i < n; i++) {              // For each element arr[i], check every         // other element arr[j] that comes after it         for (let j = i + 1; j < n; j++) {                      // Check if the sum of the current pair             // equals the target             if (arr[i] + arr[j] === target) {                 return true;             }         }     }     // If no pair is found after checking     // all possibilities     return false; }  let arr = [0, -1, 2, -3, 1]; let target = -2;  // Call the twoSum function and print the result if (twoSum(arr, target))     console.log("true"); else      console.log("false"); 

Output
true

Better Approaches - Binary Search and Hashing

We can use more methods like Binary Search and Hashing to solve this problem (Please refer Two Sum article for details) in better time complexity but Two Pointer Technique is the best solution for this problem that works well for sorted arrays.

Two-Pointer Technique - O(n) time and O(1) space

The idea of this technique is to begin with two corners of the given array. We use two index variables left and right to traverse from both corners.

Initialize: left = 0, right = n - 1
Run a loop while left < right, do the following inside the loop

  • Compute current sum, sum = arr[left] + arr[right]
  • If the sum equals the target, we’ve found the pair.
  • If the sum is less than the target, move the left pointer to the right to increase the sum.
  • If the sum is greater than the target, move the right pointer to the left to decrease the sum.

Illustration:


C++
// CPP program demonstrate working of the two // pointer technique #include <bits/stdc++.h> using namespace std;  bool twoSum(vector<int> &arr, int target){      int left = 0, right = arr.size() - 1;     while (left < right){         int sum = arr[left] + arr[right];          if (sum == target)             return true;                  // Move toward a higher sum         else if (sum < target)             left++;                 // Move toward a lower sum         else             right--;      }        // If no pair found     return false; }  int main(){     vector<int> arr = {-3, -1, 0, 1, 2};     int target = -2;     if (twoSum(arr, target))         cout << "true";     else         cout << "false";      return 0; } 
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h>  // Comparison function for qsort int compare(const void *a, const void *b){     return (*(int *)a - *(int *)b); }  // Function to check whether any pair exists // whose sum is equal to the given target value bool twoSum(int arr[], int n, int target){     // Sort the array     qsort(arr, n, sizeof(int), compare);      int left = 0, right = n - 1;      // Iterate while left pointer is less than right     while (left < right){         int sum = arr[left] + arr[right];          // Check if the sum matches the target         if (sum == target)             return true;         else if (sum < target)             left++; // Move left pointer to the right         else             right--; // Move right pointer to the left     }     // If no pair is found     return false; }  int main(){     int arr[] = {0, -1, 2, -3, 1};     int target = -2;     int n = sizeof(arr) / sizeof(arr[0]);      // Call the twoSum function and print the result     if (twoSum(arr, n, target))         printf("true\n");      else         printf("false\n");      return 0; } 
Java
import java.util.Arrays;  class GfG {      // Function to check whether any pair exists     // whose sum is equal to the given target value     static boolean twoSum(int[] arr, int target){         // Sort the array         Arrays.sort(arr);          int left = 0, right = arr.length - 1;          // Iterate while left pointer is less than right         while (left < right) {             int sum = arr[left] + arr[right];              // Check if the sum matches the target             if (sum == target)                 return true;             else if (sum < target)                 left++; // Move left pointer to the right             else                 right--; // Move right pointer to the left         }         // If no pair is found         return false;     }      public static void main(String[] args){         int[] arr = { 0, -1, 2, -3, 1 };         int target = -2;          // Call the twoSum function and print the result         if (twoSum(arr, target)) {             System.out.println("true");         }         else {             System.out.println("false");         }     } } 
Python
# Function to check whether any pair exists # whose sum is equal to the given target value def two_sum(arr, target):     # Sort the array     arr.sort()      left, right = 0, len(arr) - 1      # Iterate while left pointer is less than right     while left < right:         sum = arr[left] + arr[right]          # Check if the sum matches the target         if sum == target:             return True         elif sum < target:              left += 1  # Move left pointer to the right         else:             right -= 1 # Move right pointer to the left      # If no pair is found     return False  arr = [0, -1, 2, -3, 1] target = -2  # Call the two_sum function and print the result if two_sum(arr, target):     print("true") else:     print("false") 
C#
using System; using System.Linq;  class GfG {      // Function to check whether any pair exists     // whose sum is equal to the given target value     static bool TwoSum(int[] arr, int target){                // Sort the array         Array.Sort(arr);          int left = 0, right = arr.Length - 1;          // Iterate while left pointer is less than right         while (left < right) {             int sum = arr[left] + arr[right];              // Check if the sum matches the target             if (sum == target)                 return true;             else if (sum < target)                 left++; // Move left pointer to the right             else                 right--; // Move right pointer to the left         }         // If no pair is found         return false;     }      static void Main(){         int[] arr = { 0, -1, 2, -3, 1 };         int target = -2;          // Call the TwoSum function and print the result         if (TwoSum(arr, target))             Console.WriteLine("true");         else              Console.WriteLine("false");     } } 
JavaScript
// Function to check whether any pair exists // whose sum is equal to the given target value function twoSum(arr, target) {     // Sort the array     arr.sort((a, b) => a - b);      let left = 0, right = arr.length - 1;      // Iterate while left pointer is less than right     while (left < right) {         let sum = arr[left] + arr[right];          // Check if the sum matches the target         if (sum === target)             return true;         else if (sum < target)             left++; // Move left pointer to the right         else             right--; // Move right pointer to the left     }     // If no pair is found     return false; }  let arr = [ 0, -1, 2, -3, 1 ]; let target = -2;  // Call the twoSum function and print the result if (twoSum(arr, target)) {     console.log("true"); } else {     console.log("false"); } 

Output
true

Time Complexity: O(n) as the loops runs at most n times. We either increase left, or decrease right or stop the loop.
Auxiliary Space: O(1)

How does this work?

We need to prove that we never miss a valid pair.

Case 1 ( When we increment left ) In this case we simply ignore current arr[left] and move to the next element by doing left++. We do this when arr[left] + arr[right] is smaller than the target. The reason this step is safe is, if arr[left] is giving a smaller value than sum, then it will given even much less values for the elements before arr[right]. Now how about the elements after arr[right]? Note that we moved right when we were sure that no pair can be formed with the current right (arr[right] was too high), so arr[left] can not form a pair with those values also.

Case 2 (When we decrement right) We can use the same reasoning (as we discussed for left) to prove that we never miss out a valid pair.

More problems based on two pointer technique. 

  • Top Problems for Two Pointers
  • Coding Practice on Two Pointer Algorithms

Next Article
Java Program for Two Pointers Technique
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Misc
  • Searching
  • Technical Scripter
  • DSA
  • Arrays
  • two-pointer-algorithm
Practice Tags :
  • Arrays
  • Misc
  • Searching
  • two-pointer-algorithm

Similar Reads

    Two Pointers Technique
    Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists an
    11 min read

    Two Pointers Technique in Different languages

    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 so
    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 so
    3 min read

    Problems based on Two-Pointer Technique

    Find four elements that sum to a given value | Two-Pointer approach
    Given an array arr of integers of size N and a target number, the task is to find all unique quadruplets in it, whose sum is equal to the target number. Examples:Input: arr[] = {4, 1, 2, -1, 1, -3], target = 1 Output: [[-3, -1, 1, 4], [-3, 1, 1, 2]] Explanation: Both the quadruplets sum equals to ta
    10 min read
    Rearrange an array in maximum minimum form using Two Pointer Technique
    Given a sorted array of positive integers, rearrange the array alternately i.e first element should be a maximum value, at second position minimum value, at third position second max, at fourth position second min, and so on. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2
    6 min read
    Pair with largest sum which is less than K in the array
    Given an array arr of size N and an integer K. The task is to find the pair of integers such that their sum is maximum and but less than K Examples: Input : arr = {30, 20, 50} , K = 70 Output : 30, 20 30 + 20 = 50, which is the maximum possible sum which is less than K Input : arr = {5, 20, 110, 100
    10 min read
    Longest increasing sequence by the boundary elements of an Array
    Given an array arr[] of length N with unique elements, the task is to find the length of the longest increasing subsequence that can be formed by the elements from either end of the array.Examples: Input: arr[] = {3, 5, 1, 4, 2} Output: 4 Explanation: The longest sequence is: {2, 3, 4, 5} Pick 2, Se
    8 min read
    Two Sum - Pair with given Sum
    Given an array arr[] of n integers and a target value, the task is to find whether there is a pair of elements in the array whose sum is equal to target. This problem is a variation of 2Sum problem.Examples: Input: arr[] = [0, -1, 2, -3, 1], target = -2Output: trueExplanation: There is a pair (1, -3
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences