Array & StringBeginner
Two Pointers
Use two pointers that move toward each other or in the same direction to efficiently search or compare elements in a sorted array or string.
Problem: Two Sum II (Sorted Array)
Find two numbers in the sorted array [1, 2, 4, 6, 8, 10] that add up to 10.
1
2
4
6
8
10
L
R
Initialize pointers at both ends
Left pointer at index 0 (value 1), Right pointer at index 5 (value 10). Target sum = 10.
Sum: 11Target: 10> Too high
Step 1/5
Speed:
When to Use
- Sorted array with a target sum or condition
- Comparing elements from both ends
- Removing duplicates in-place
- Palindrome checking
Key Indicators
- Sorted array/string
- Find pair/triplet with a condition
- In-place operations
- Comparing from both ends
Complexity
Time
O(n)
Space
O(1)
Common Problems
Two Sum II (sorted)3SumContainer With Most WaterTrapping Rain WaterValid PalindromeRemove Duplicates from Sorted Array
Code
left = 0, right = n - 1
while left < right:
if condition_met(arr[left], arr[right]):
return result
if need_larger_sum:
left++
else:
right--Want all 29 patterns with detailed visual walkthroughs?
The complete book includes 84 practice problems, full decision tree, and illustrated step-by-step solutions.
Book Coming Soon ($4.99)