Two Pointers Pattern
Master the two pointers technique for efficient array traversal
beginner
Two Pointers Pattern
The Two Pointers technique uses two pointers to traverse a data structure, often from opposite ends or at different speeds.
When to Use
- Working with sorted arrays
- Finding pairs that satisfy a condition
- In-place array modifications
- Reducing O(n²) to O(n)
Interactive Visualization
This example finds two numbers that sum to a target value:
Two Sum with Two Pointers
Interactive
Sorted
Find two numbers that sum to 50 in sorted array
Speed
Step 1 of 8
Implementation
1function twoSum(arr, target) {2 // Array must be sorted3 let left = 0;4 let right = arr.length - 1;5 6 while (left < right) {7 const sum = arr[left] + arr[right];8 9 if (sum === target) {10 return [left, right];11 } else if (sum < target) {12 left++;13 } else {14 right--;15 }16 }17 return null; // No pair found18}How It Works
- Initialize two pointers (usually start and end)
- Calculate current result based on pointer positions
- Move pointers based on comparison with target:
- Too small? Move left pointer right
- Too big? Move right pointer left
- Found? Return result
Complexity
| Metric | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
Common Variations
Opposite Ends
Start from both ends, move towards center.
Same Direction
Both pointers start from same end, move at different speeds.
Slow & Fast Pointer
One moves 1 step, other moves 2 steps (cycle detection).
Practice Problems
- Container With Most Water
- 3Sum
- Remove Duplicates from Sorted Array
- Valid Palindrome
Common Use Cases
- Finding pairs that sum to target
- Removing duplicates
- Reversing arrays
- Checking palindromes
Related Topics
arrays two-pointers optimization
Ad