ššTwo Pointer Pattern
Learn how to use two pointers to solve array problems in linear time, turning O(n²) brute force into elegant O(n) solutions.
šIntroduction
Imagine you're at a library with books arranged by height on a shelf. You need to find two books whose combined height equals exactly 16 inches.
The Two Pointer pattern is one of the most elegant techniques in algorithm design. Instead of comparing every possible pair of elements (which takes O(n²) time), we use two pointers that move toward each other, solving the problem in just one pass through the array.
When to use Two Pointers?
- ā The array is sorted (or can be sorted)
- ā You need to find pairs, triplets, or subarrays
- ā You want to compare elements from different ends
- ā You need to partition or rearrange elements in-place
š¤The Problem
Classic Problem: Two Sum (Sorted Array)
Given a sorted array of integers and a target sum, find two numbers that add up to the target.
Brute Force: Check every pair ā O(n²) time
Two Pointer: Start from both ends ā O(n) time
š”The Insight
Because the array is sorted, we can make intelligent decisions:
Sum too small? š¼
Move the left pointer right to pick a larger number.
Sum too large? š½
Move the right pointer left to pick a smaller number.
This way, we eliminate possibilities with each step, guaranteeing we find the answer (if it exists) in at most n steps!
šSee It In Action
Watch how two pointers move through the array to find the target sum of 14.
Ready to start
1function findPairWithSum(arr, target) {2 let left = 0, right = arr.length - 1;34 while (left < right) {5 const sum = arr[left] + arr[right];6 if (sum === target) return [left, right];78 if (sum < target) left++;9 else right--;10 }11 return null;12}
šļøComplexity Race
See the dramatic difference between brute force O(n²) and two pointer O(n).
ā” Complexity Race
Watch how Two Pointer O(n) beats Brute Force O(n²)
Brute Force
O(n²)
0
/ 400 ops
Two Pointer
O(n)
0
/ 20 ops
š®Practice Challenges
Now it's your turn! Control the pointers to find the target sum.
Find the Pair
easyFind two numbers that add up to the target
Left Pointer
Right Pointer
Larger Array
mediumSame concept, bigger challenge
Left Pointer
Right Pointer
Edge Cases
hardHandle the tricky spots
Left Pointer
Right Pointer
ā Summary
Key Takeaways
- Two pointers work best on sorted arrays
- Move pointers based on comparison with target
- Time complexity: O(n) vs O(n²) brute force
- Space complexity: O(1) - no extra space needed
Common Variations
- ⢠Three Sum (3 pointers)
- ⢠Container With Most Water
- ⢠Remove Duplicates In-Place
- ⢠Palindrome Check
- ⢠Dutch National Flag Problem