๐๐ Two Pointers Technique
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
- Start with
left = 0,right = n-1 - Calculate
sum = arr[left] + arr[right] - If
sum == target: Found it! โ - If
sum < target: Moveleft++(need larger sum) - If
sum > target: Moveright--(need smaller sum) - Repeat until
left >= right
See It in Action
The Code
Click Run to execute your code
- 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:
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
- Pattern: Start from both ends, move based on comparison
- Complexity: O(n) time, O(1) space - much better than O(nยฒ)
- 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.
Enjoying these tutorials?