Arrays January 01 ,2026

Two Pointers Technique – 

1. Introduction

The Two Pointers Technique is an algorithmic approach where two indices (pointers) are used to traverse a data structure in a coordinated manner to solve problems efficiently.

Instead of checking every possible combination (which is slow), we intelligently move pointers based on conditions, reducing unnecessary computations.

This technique is widely used in:

  • Arrays
  • Strings
  • Linked Lists

2. Why Two Pointers?

Many problems involve:

  • Finding pairs
  • Checking ranges
  • Comparing elements from both ends

A brute-force approach usually leads to O(n²) time complexity.
Two pointers often reduce it to O(n).

3. When to Use Two Pointers

Use this technique when:

  1. Input is sorted
    • Pair sum
    • Closest sum
    • Triplets
  2. Pair / Range based problems
    • Subarrays
    • Palindrome checking
  3. Sliding window problems
    • Longest substring
    • Smallest subarray with sum ≥ K
  4. Linked list traversal
    • Detecting cycles
    • Finding middle node

4. Problem Statement (Example)

Sum of Pair Equal to Target

Given:
A sorted array arr[] of integers and an integer target.

Task:
Check whether there exists a pair (arr[i], arr[j]) such that:

arr[i] + arr[j] == target

5. Illustration (Language Independent)

Example

Array:  [-8, 1, 4, 6, 10, 45]
Target: 16
Index:   0   1   2   3   4    5
Array:  -8   1   4   6  10   45
         ↑                     ↑
       left                 right
Sum = -8 + 45 = 37  → too large → move right
Index:   0   1   2   3   4    5
Array:  -8   1   4   6  10   45
         ↑                ↑
       left            right
Sum = -8 + 10 = 2  → too small → move left
Index:   0   1   2   3   4    5
Array:  -8   1   4   6  10   45
             ↑        ↑
           left     right
Sum = 6 + 10 = 16  ✅ FOUND

6. Algorithm (Two Pointer Technique)

  1. Initialize two pointers:
    • left = 0
    • right = n - 1
  2. While left < right:
    • Compute sum = arr[left] + arr[right]
    • If sum == target → return true
    • If sum < target → left++
    • If sum > target → right--
  3. If loop ends → return false

7. Why This Algorithm Works 

Case 1: Sum < Target → Move Left

  • Current left value is too small
  • Moving right further only decreases possibilities
  • Safe to discard arr[left]

Case 2: Sum > Target → Move Right

  • Current right value is too large
  • Moving left pointer increases sum
  • Safe to discard arr[right]

✔ Because the array is sorted, we never miss a valid pair

Implementations in All Languages

 C++ Implementation

#include 
#include 
using namespace std;

bool twoSum(vector& arr, int target) {
    int left = 0, right = arr.size() - 1;

    while (left < right) {
        int sum = arr[left] + arr[right];

        if (sum == target)
            return true;
        else if (sum < target)
            left++;
        else
            right--;
    }
    return false;
}

int main() {
    vector arr = {-8, 1, 4, 6, 10, 45};
    int target = 16;

    cout << (twoSum(arr, target) ? "true" : "false");

    return 0;
}

Output

true

 C Implementation

#include 

int twoSum(int arr[], int n, int target) {
    int left = 0, right = n - 1;

    while (left < right) {
        int sum = arr[left] + arr[right];

        if (sum == target)
            return 1;
        else if (sum < target)
            left++;
        else
            right--;
    }

    return 0;
}

int main() {

    int arr[] = {-8, 1, 4, 6, 10, 45};
    int target = 16;
    int n = sizeof(arr) / sizeof(arr[0]);

    printf(twoSum(arr, n, target) ? "true" : "false");

    return 0;
}

Output

true

 Java Implementation

class TwoSum {

    static boolean twoSum(int[] arr, int target) {

        int left = 0, right = arr.length - 1;

        while (left < right) {

            int sum = arr[left] + arr[right];

            if (sum == target)
                return true;
            else if (sum < target)
                left++;
            else
                right--;
        }

        return false;
    }

    public static void main(String[] args) {

        int[] arr = {-8, 1, 4, 6, 10, 45};
        int target = 16;

        System.out.println(twoSum(arr, target));
    }
}

Output

true

 Python Implementation

def two_sum(arr, target):

    left = 0
    right = len(arr) - 1

    while left < right:

        s = arr[left] + arr[right]

        if s == target:
            return True
        elif s < target:
            left += 1
        else:
            right -= 1

    return False


arr = [-8, 1, 4, 6, 10, 45]
target = 16

print(two_sum(arr, target))

Output

True

C# Implementation

using System;

class Program {

    static bool TwoSum(int[] arr, int target) {

        int left = 0;
        int right = arr.Length - 1;

        while (left < right) {

            int sum = arr[left] + arr[right];

            if (sum == target)
                return true;
            else if (sum < target)
                left++;
            else
                right--;
        }

        return false;
    }

    static void Main() {

        int[] arr = {-8, 1, 4, 6, 10, 45};
        int target = 16;

        Console.WriteLine(TwoSum(arr, target));
    }
}

Output

True

JavaScript Implementation

function twoSum(arr, target) {

    let left = 0;
    let right = arr.length - 1;

    while (left < right) {

        let sum = arr[left] + arr[right];

        if (sum === target)
            return true;
        else if (sum < target)
            left++;
        else
            right--;
    }

    return false;
}

let arr = [-8, 1, 4, 6, 10, 45];
let target = 16;

console.log(twoSum(arr, target));

Output

true

 

9. Time and Space Complexity

MetricValue
Time ComplexityO(n)
Space ComplexityO(1)

10. Summary

  • Two Pointers is one of the most important interview techniques
  • Works best on sorted data
  • Reduces time from O(n²) → O(n)
  • Used in many advanced problems like:
    • Three Sum
    • Trapping Rain Water
    • Sliding Window problems

Next Blog-
Prefix Sum Technique

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Array Memo...
Arrays December 12 ,2025

Array Memory Represe...

Array Oper...
Arrays December 12 ,2025

Array Operations and...

Advantages...
Arrays December 12 ,2025

Advantages and Disad...

Arrays in...
Arrays December 12 ,2025

Arrays in C

Vector in...
Arrays December 12 ,2025

Vector in C++ STL

Arrays vs...
Arrays December 12 ,2025

Arrays vs ArrayList...

JavaScript...
Arrays December 12 ,2025

JavaScript Arrays

Binary Sea...
Arrays December 12 ,2025

Binary Search on Arr...

Prefix Sum...
Arrays January 01 ,2026

Prefix Sum Technique

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com