Back to Academy
patterns
Two Pointers
The two pointers technique uses two references that traverse a data structure simultaneously, either from opposite ends moving inward or at different speeds (fast/slow). It reduces nested loops to a single pass, turning O(n²) brute-force solutions into O(n) linear scans on sorted or sequential data.
Use Cases
- •Finding pairs in a sorted array that sum to a target
- •Detecting cycles in a linked list with fast/slow pointers
- •Removing duplicates from a sorted array in-place
Complexity Analysis
| Metric | Best | Average | Worst |
|---|---|---|---|
| Time | O(n) | O(n) | O(n) |
| Space | O(1) | ||
Visualization
Target:18
Implementation
Output
Click "Run Code" to see output...