Two-Pointer Technique: Opposite-Direction & Fast-Slow Patterns
Two-Pointer Technique: Opposite-Direction & Fast-Slow Patterns
The Two-Pointer Technique is an algorithmic pattern that uses two pointer indices to coordinate searches or mutations across an array or sequence. By moving pointers intelligently based on problem constraints, two-pointer algorithms reduce brute-force $O(n^2)$ quadratic nested loops into blazing $O(n)$ linear time with $O(1)$ auxiliary space.
1. Real-World Analogy: Folding a Ruler or Reading a Word
Imagine inspecting whether a word like "RADAR" is a palindrome:
- You don't make a second copy of the word and check every combination.
- Instead, you place your left index finger on the first letter
'R'and your right index finger on the last letter'R'. - You verify they match, then slide your fingers inward simultaneously. If your fingers meet in the middle without any mismatches, it is a palindrome!
2. The Two Core Categories of Two Pointers
Category 1: Opposite-Direction Pointers (Converging)
- Pointer
leftstarts at index0. - Pointer
rightstarts at indexn - 1. - Pointers advance towards each other (
left++,right--) until they meet. - Top Applications: Reversing arrays, Palindrome checking, Two Sum in Sorted Array, Container with Most Water.
Category 2: Same-Direction Pointers (Fast & Slow)
- Pointer
slowtracks the boundary of clean/valid data. - Pointer
fastscans forward through the array. - Top Applications: In-place element removal, deduplicating sorted arrays, moving zeros.
3. Classic Problem 1: Two Sum in a Sorted Array ($O(n)$)
Given a 1-indexed array of integers numbers sorted in non-decreasing order, find two numbers such that they add up to a specific target number:
Python 3 Implementation:
Modern JavaScript / TypeScript Implementation:
4. Classic Problem 2: Remove Duplicates from Sorted Array In-Place
Remove duplicates in-place such that each unique element appears only once, returning the count of unique items.
Python 3:
5. Trace Table: nums = [1, 1, 2, 2, 3]
read_idx (Fast) | Current Value | Previous Value | Is Unique? | Action | Modified Array |
|---|---|---|---|---|---|
| 1 | 1 | 1 | No | Skip | [1, 1, 2, 2, 3] |
| 2 | 2 | 1 | Yes | nums[1] = 2, write++ | [1, 2, 2, 2, 3] |
| 3 | 2 | 2 | No | Skip | [1, 2, 2, 2, 3] |
| 4 | 3 | 2 | Yes | nums[2] = 3, write++ | [1, 2, 3, 2, 3] |
Result: First 3 elements are [1, 2, 3]. Return length 3 in $O(n)$ time with $O(1)$ space!
Multiple Choice Questions
Sliding Window Algorithm: Fixed & Dynamic Window Strategies
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.