Two Pointer Technique

The two-pointer technique uses two index variables that traverse an array (or string) — either moving toward each other, moving in the same direction, or moving through two separate arrays — to solve problems in O(n) time without needing nested loops or extra data structures.

When to Use Two Pointers

This pattern shines when the input is sorted, or when you need to compare/combine elements from opposite ends of a collection, or track a pair/triplet that satisfies some condition. Whenever your brute-force instinct is a nested loop (O(n²)), ask: "can two pointers replace one of those loops?"

The Three Common Variants

Time & Space Complexity

Problem Type Brute Force Two Pointer
Pair with target sum (sorted array)O(n²)O(n)
Reverse array in placeO(n) + O(n) spaceO(n), O(1) space
Remove duplicates in-placeO(n²)O(n)
Merge two sorted arraysO((n+m) log(n+m))O(n+m)

Illustration: Converging Pointers

Two Pointer Technique Illustration

C++ Example: Two Sum on a Sorted Array

two_sum_sorted.cpp
#include <iostream>
#include <vector>
using namespace std;

pair<int,int> twoSumSorted(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 {left, right};
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    return {-1, -1};
}

Python Example: Common Two Pointer Patterns

two_pointer_patterns.py
# 1. Check if a string is a palindrome (converging pointers)
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1
        right -= 1
    return True

# 2. Remove duplicates from a sorted array in-place (same-direction pointers)
def remove_duplicates(nums):
    if not nums:
        return 0
    slow = 0
    for fast in range(1, len(nums)):
        if nums[fast] != nums[slow]:
            slow += 1
            nums[slow] = nums[fast]
    return slow + 1  # new length

# 3. Merge two sorted arrays (two pointers, two arrays)
def merge_sorted(a, b):
    i, j = 0, 0
    merged = []
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            merged.append(a[i])
            i += 1
        else:
            merged.append(b[j])
            j += 1
    merged.extend(a[i:])
    merged.extend(b[j:])
    return merged

Quiz

You have a sorted array and need to find if any pair sums to a target value. What's the optimal time complexity using two pointers?

Practice on LeetCode

Once you're comfortable with the concepts above, try solving these problems to reinforce your understanding:

← Back to DSA