πββοΈ Two Pointers: The Dance of Two Friends
Imagine you have a long rope with colorful beads on it. Now, picture two friendsβLeft and Rightβstanding at different spots on this rope. They can walk toward each other, away from each other, or even chase one another! This is exactly how the Two Pointers technique works in programming.
π― What is Two Pointers?
Think of it like this:
You have a line of kids, and you need to find two kids whose heights add up to exactly 10 feet.
Instead of checking every pair (which takes forever!), you put one friend at the start and another at the end. They walk toward each other, adjusting based on what they find.
Why is this magical? πͺ
- Checking every pair: Very slow (like checking 100 Γ 100 = 10,000 pairs!)
- Two pointers: Super fast (just 100 steps at most!)
πͺ The Five Amazing Tricks
Letβs learn five super cool tricks using our two friends, Left and Right!
1οΈβ£ Two Pointers Technique (The Basic Dance)
The Story π
Imagine a sorted line of numbered boxes:
[1, 2, 4, 6, 8, 10]
You need to find two boxes that add up to 10.
The Dance:
- Left starts at
1, Right starts at10 1 + 10 = 11β Too big! Right moves left1 + 8 = 9β Too small! Left moves right2 + 8 = 10β Perfect! π
The Code π»
def find_pair(nums, target):
left = 0
right = len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return []
Visual Flow π
graph TD A[Start: Left=0, Right=End] --> B{Sum = Target?} B -->|Yes| C[Found! Return pair] B -->|Sum < Target| D[Move Left forward] B -->|Sum > Target| E[Move Right backward] D --> F{Left < Right?} E --> F F -->|Yes| B F -->|No| G[No pair found]
2οΈβ£ Three Sum Pattern (Three Friends Join!)
The Story π
Now imagine THREE friends need to hold hands, and their jersey numbers must add up to 0!
Given: [-4, -1, -1, 0, 1, 2]
The Trick:
- Fix one friend (say
-1) - Use two pointers for the other two!
- Find pairs that add to
0 - (-1) = 1
The Code π»
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums) - 2):
# Skip duplicates
if i > 0 and nums[i] == nums[i-1]:
continue
left = i + 1
right = len(nums) - 1
target = -nums[i]
while left < right:
curr_sum = nums[left] + nums[right]
if curr_sum == target:
result.append([nums[i],
nums[left],
nums[right]])
left += 1
right -= 1
# Skip duplicates
while left < right and \
nums[left] == nums[left-1]:
left += 1
elif curr_sum < target:
left += 1
else:
right -= 1
return result
Example π―
Input: [-1, 0, 1, 2, -1, -4]
| Fixed | Left | Right | Sum | Action |
|---|---|---|---|---|
| -4 | -1 | 2 | -3 | Move left |
| -1 | -1 | 2 | 0 | Found! β |
| -1 | 0 | 1 | 0 | Found! β |
Output: [[-1, -1, 2], [-1, 0, 1]]
3οΈβ£ Container With Most Water (The Water Game!)
The Story π
Picture a row of walls with different heights:
| |
| | | |
| | | | |
0 1 2 3 4
Heights: [1,8,6,2,5]
You want to trap the MOST water between any two walls!
The Secret:
- Water height = shorter wall
- Water area = height Γ distance
Why Two Pointers Work:
- Start with widest container (left=0, right=end)
- Move the SHORTER wall inward (maybe find taller one!)
The Code π»
def max_area(height):
left = 0
right = len(height) - 1
max_water = 0
while left < right:
width = right - left
h = min(height[left], height[right])
area = width * h
max_water = max(max_water, area)
# Move shorter wall
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_water
Visual Example π
Heights: [1, 8, 6, 2, 5, 4, 8, 3, 7]
Step 1: left=0(1), right=8(7)
Area = 8 Γ min(1,7) = 8
Move left (shorter)
Step 2: left=1(8), right=8(7)
Area = 7 Γ min(8,7) = 49 β¨
Move right (shorter)
4οΈβ£ Valid Palindrome (The Mirror Game!)
The Story π
A palindrome reads the same forwards and backwards, like:
- βracecarβ β β
- βA man, a plan, a canal: Panamaβ β β
- βhelloβ β β
The Trick:
- Left friend starts at the beginning
- Right friend starts at the end
- They walk toward each other, checking if letters match!
The Code π»
def is_palindrome(s):
# Clean: keep only letters/numbers
s = ''.join(c.lower() for c in s
if c.isalnum())
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
Walk Through πΆ
String: "racecar"
Step 1: 'r' == 'r' β (left=0, right=6)
Step 2: 'a' == 'a' β (left=1, right=5)
Step 3: 'c' == 'c' β (left=2, right=4)
Step 4: left=3, right=3 (same spot!)
Result: PALINDROME! π
graph TD A[Start: L=0, R=n-1] --> B{char at L == char at R?} B -->|Yes| C[Move both inward] B -->|No| D[NOT a palindrome] C --> E{L >= R?} E -->|Yes| F[IS a palindrome!] E -->|No| B
5οΈβ£ Trapping Rain Water (The Puddle Problem!)
The Story π
After rain, water gets trapped between tall buildings:
β
β ββ β
β ββ ββββ β
-----------
[0,1,0,2,1,0,1,3,2,1,2,1]
Water fills up to the shorter of the two tallest walls on either side!
Two Pointer Magic:
- Track the tallest wall seen from left
- Track the tallest wall seen from right
- Water at any position = min(maxLeft, maxRight) - height
The Code π»
def trap(height):
if not height:
return 0
left = 0
right = len(height) - 1
left_max = height[left]
right_max = height[right]
water = 0
while left < right:
if left_max < right_max:
left += 1
left_max = max(left_max, height[left])
water += left_max - height[left]
else:
right -= 1
right_max = max(right_max, height[right])
water += right_max - height[right]
return water
Step-by-Step π§
Heights: [0, 1, 0, 2, 1, 0, 1, 3]
L=0, R=7: left_max=0, right_max=3
β Move left (0 < 3)
L=1, R=7: left_max=1, right_max=3
β water += 1-1 = 0
β Move left
L=2, R=7: left_max=1, right_max=3
β water += 1-0 = 1 π§
β Move left
L=3, R=7: left_max=2, right_max=3
β water += 2-2 = 0
β Move left
...continue until they meet!
π The Big Picture
| Problem | When to Use | Key Insight |
|---|---|---|
| Two Sum | Sorted array, find pair | Move toward target |
| Three Sum | Find triplets = 0 | Fix one, two-pointer rest |
| Container | Max area between lines | Shorter wall limits water |
| Palindrome | Check symmetry | Compare from both ends |
| Trap Water | Water between heights | Track max from both sides |
π Key Takeaways
- Two Pointers = Two Friends moving along data
- Usually works on sorted arrays or symmetry problems
- Reduces time from O(nΒ²) to O(n)
- Move pointers based on comparison logic
- Perfect for finding pairs, checking symmetry, or optimization
π Remember This!
When you see a problem about finding pairs, checking both ends, or optimizing something with two endsβthink Two Pointers!
Itβs like having two scouts exploring from different directions, meeting in the middle with the answer! π