Two-Pointer Algorithm

Visualize the two-pointer technique for finding pairs in a sorted array that sum to a target

Array

2
0
3
1
5
2
7
3
11
4
13
5
17
6
19
7
23
8
29
9

Current Operation:

Ready to search. Enter a target sum and click "Start" to begin.

Comparisons

0

Time Complexity

O(n)

Space Complexity

O(1)

Array Size

10

Color Coding:

Found Pair
Comparing
Left Pointer
Right Pointer
Discarded

Target Sum:

Simulation

SlowFast
800ms

Current Array:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

What is the Two-Pointer Technique?

The Two-Pointer technique is an efficient algorithm pattern that uses two pointers traversing an array from different positions to solve problems in O(n) time with O(1) extra space. It's particularly effective for sorted arrays.

How It Works

For finding two numbers that sum to a target in a sorted array:

  1. Initialize two pointers: left = 0 and right = length - 1
  2. Calculate the sum of elements at both pointers
  3. If sum equals target, we found the pair!
  4. If sum is less than target, move left pointer right (need larger sum)
  5. If sum is greater than target, move right pointer left (need smaller sum)
  6. Repeat until pointers meet or pair is found

Implementation

Python implementation:

from typing import List, Optional

def two_sum_sorted(arr: List[int], target: int) -> Optional[List[int]]:
    """
    Find two numbers in a sorted array that sum to target using two-pointer technique.
    
    Uses two pointers starting at opposite ends, moving them based on whether
    the current sum is too small or too large. Only works for sorted arrays.
    
    Args:
        arr: Sorted list of integers (ascending order).
        target: Target sum to find.
    
    Returns:
        List containing two indices [i, j] where arr[i] + arr[j] == target,
        or None if no such pair exists.
    
    Time Complexity: O(n) where n is array length.
    Space Complexity: O(1).
    """
    left, right = 0, len(arr) - 1
    
    while left < right:
        current_sum = arr[left] + arr[right]
        
        if current_sum == target:
            return [left, right]  # Found pair
        elif current_sum < target:
            left += 1  # Need larger sum, move left pointer right
        else:
            right -= 1  # Need smaller sum, move right pointer left
    
    return None  # No pair found

# Example
arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
target = 24
result = two_sum_sorted(arr, target)
if result:
    print(f"Found at indices: {result}")  # Found at indices: [1, 4]
    print(f"Values: {arr[result[0]]} + {arr[result[1]]} = {target}")
else:
    print("No pair found")

Time & Space Complexity

Time Complexity:

  • Best/Average/Worst: O(n) - Each element is visited at most once

Space Complexity: O(1) - Only uses a constant amount of extra space for the two pointers

Key Requirement: The two-pointer technique for sum problems requires a sorted array. The array must be sorted in ascending order for the algorithm to work correctly.

Real-World Applications

  • Two Sum problems: finding pairs that sum to a target
  • Three Sum: finding triplets with zero sum
  • Removing duplicates: from sorted arrays efficiently
  • Validating palindromes: checking if array/string is palindrome
  • Container with most water: finding maximum area
  • Merging sorted arrays: combining two sorted arrays