Web Analytics

๐Ÿ‘‰๐Ÿ‘ˆ Two Pointers Technique

Beginner to Intermediate ~12 min read

You need to find two numbers in a sorted array that sum to a target. The naive approach checks every pair - that's 4,950 comparisons for 100 numbers! The two pointers technique does it in just 100 steps. Let's see how.

The Problem: Two Sum

Given a sorted array, find two numbers that add up to a target value.

Example

Array:  [1, 2, 3, 4, 6, 8, 9]
Target: 10
Answer: indices 2 and 5 (3 + 7 doesn't exist, but 4 + 6 = 10)

Naive approach: Check every pair โ†’ O(nยฒ)

Two pointers: Work from both ends โ†’ O(n)

How Two Pointers Works

The key insight: In a sorted array, you can eliminate half the search space with each comparison.

The Algorithm

  1. Start with left = 0, right = n-1
  2. Calculate sum = arr[left] + arr[right]
  3. If sum == target: Found it! โœ…
  4. If sum < target: Move left++ (need larger sum)
  5. If sum > target: Move right-- (need smaller sum)
  6. Repeat until left >= right

See It in Action

The Code

Output
Click Run to execute your code
Why it works:
  • If sum is too small, the only way to increase it is to move left pointer right
  • If sum is too large, the only way to decrease it is to move right pointer left
  • This eliminates one element per step โ†’ O(n) time!

Quick Quiz

  • Why does this only work on sorted arrays?
    Show answer Because we rely on the fact that moving left increases the sum and moving right decreases it. This only holds if the array is sorted!
  • What if the array isn't sorted?
    Show answer Sort it first! Sorting is O(n log n), but that's still better than O(nยฒ) for checking all pairs.

Three Common Patterns

Two pointers isn't just for two sum. Here are the main patterns:

Output
Click Run to execute your code
Pattern When to Use Example
Opposite Ends Sorted array, find pairs/triplets Two sum, three sum
Same Direction In-place modifications Remove duplicates, partition
Sliding Window Subarrays of fixed/variable size Max sum subarray, longest substring

When to Use Two Pointers

โœ… Use Two Pointers When:

  • Array is sorted (or can be sorted)
  • Need to find pairs/triplets that satisfy a condition
  • Removing duplicates in-place
  • Reversing or checking palindromes
  • Partitioning arrays

โŒ Don't Use When:

  • Array can't be sorted (order matters)
  • Need to preserve original indices
  • Looking for single elements (use binary search instead)

Common Mistakes

โŒ Forgetting to Sort

arr = [3, 1, 4, 2]  # Not sorted!
two_sum(arr, 5)  # Won't work correctly

Fix: arr.sort() first

โŒ Wrong Pointer Movement

if sum < target:
    right -= 1  # Wrong! Should be left += 1

Remember: Too small โ†’ move left. Too large โ†’ move right.

Summary

The 3-Point Two Pointers Guide

  1. Pattern: Start from both ends, move based on comparison
  2. Complexity: O(n) time, O(1) space - much better than O(nยฒ)
  3. Requirement: Array must be sorted (or sortable)

Interview tip: When you see "sorted array" and "find pair", think two pointers!

What's Next?

You've mastered two pointers! Next up: Sliding Window - a variation of two pointers for finding optimal subarrays. It's one of the most powerful patterns for string and array problems.

Practice: Try solving "3Sum" (find three numbers that sum to target) using two pointers. Hint: Fix one number, then use two pointers on the rest!