Two Pointers on a Sorted Array
Compare the current pair with the target. Use the sorted order to decide which endpoint can move.
Core Intuition & How It Works
The two-pointers technique moves two indices across a sorted array or sequence to find pairs, partitions, or palindromes in linear time. Monotonic ordering lets each comparison rule out an entire row or column of pairs at once.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n) after sorting |
| Space Complexity | O(1) |
| Topic Chapter | Chapter 3: Array & String Techniques |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Start pointers at opposite ends (converging) or at the same end (fast/slow writer) whenever pointer movement never needs to backtrack.
Common Pitfalls & Edge Cases
Forgetting that converging sum searches require sorted input, or mishandling duplicate elements in multi-sum problems.
Real-World & Technical Interview Applications
Two-Sum on sorted arrays, container with most water, in-place deduplication, and merging sorted sequences.