Mastering Two Pointer Technique in Python

A simple and powerful approach to solve array problems efficiently.

What is Two Pointer?

The two pointer technique uses two indices to iterate over an array, usually from opposite ends or at different speeds, to reduce time complexity.

Example Problem

Given a sorted array, find if there exists a pair that sums to a target.

def two_sum(arr, target):
      left, right = 0, len(arr) - 1
  
      while left < right:
          curr = arr[left] + arr[right]
  
          if curr == target:
              return True
          elif curr < target:
              left += 1
          else:
              right -= 1
  
      return False

Why It Works

Since the array is sorted, we can intelligently move pointers instead of checking all pairs, reducing complexity from O(n²) to O(n).

When to Use