Two Pointers
⏱ Time: O(n)💾 Space: O(1)
Use two pointers (usually left and right) to traverse an array from both ends toward the center, or both from the start at different speeds. Works best on sorted arrays or when you need to find pairs/triplets.
🎯 When to Use
- ✓Array is sorted (or can be sorted)
- ✓Finding pairs that satisfy a condition
- ✓Comparing elements from both ends
- ✓Palindrome checking
- ✓Removing duplicates in-place
📝 Pseudocode
Two Pointers TemplateO(n)
1function twoPointers(arr, target): 2 left = 0 3 right = arr.length - 1 4 5 while left < right: 6 sum = arr[left] + arr[right] 7 if sum == target: 8 return [left, right] 9 else if sum < target: 10 left++ // need bigger sum 11 else: 12 right-- // need smaller sum 13 14 return NOT_FOUND
🏢 Real-World Use Cases
Amazon
Package weight matching
Finding two packages whose combined weight exactly fills a container — sorted by weight, two-pointer scan.
Google
Search result deduplication
Merging sorted result lists from multiple indexes while removing duplicates using two pointers.