Scanning from both ends
Day 107 of 149
π Full deep-dive with code examples
The Dance Partners Analogy
Imagine a line of people finding dance partners:
- One person starts from the left
- Another starts from the right
- They move toward each other until matched
Two Pointers works like this!
Two markers that move through data, often toward each other.
The Problem It Solves
Some problems need comparing pairs:
- "Find two numbers that add to 10"
- "Is this word a palindrome?"
- "Remove duplicates from a sorted list"
Checking every possible pair is slow (every item with every other item).
How It Works
Instead of checking all pairs:
- Start with two pointers (often at opposite ends)
- Move them based on conditions
- Stop when they meet or find the answer
This is much faster because you eliminate many options with each move!
Classic Examples
Finding a pair that sums to target (sorted array):
Array: [1, 3, 5, 7, 9] Target: 12
Leftβ 1 Rightβ 9 Sum=10 (too small, move left)
Leftβ 3 Rightβ 9 Sum=12 β Found!
Checking palindrome:
"racecar"
Lβ r Rβ r Match!
Lβ a Rβ a Match!
Lβ c Rβ c Match!
Lβ e Rβ e (they meet) It's a palindrome!
When To Use It
Two pointers works great when:
- Data is sorted
- Comparing elements from different positions
- Finding pairs or ranges
Think: "Can I use two markers moving toward each other?"
In One Sentence
Two Pointers uses two markers moving through data to efficiently find pairs or ranges without checking every combination.
π Enjoying these? Follow for daily ELI5 explanations!
Making complex tech concepts simple, one day at a time.
Top comments (0)