Two Pointers
Uses two indices to scan or compare elements in an array or string efficiently.
The Approach
- Initialize two pointers, often at opposite ends of a sorted array or at the start.
- Move the pointers inward or forward based on a condition.
- Process elements at the pointers (e.g., compare them, check their sum).
- Stop when the pointers meet or cross.
Types of Two Pointers
Opposite Ends
Pointers start at the beginning and end, moving towards each other. Common in sorted arrays.
2
7
11
15
L
R
Initialize pointers at both ends.
Fast & Slow
One pointer moves faster than the other. Used to detect cycles or find middle elements.
2
7
11
15
L
R
Initialize pointers at both ends.
Common Problems
Two Sum II (Input Array Is Sorted)
Two Pointers
Container With Most Water
Two Pointers
Valid Palindrome
Two Pointers
Remove Duplicates from Sorted Array
Two Pointers
3Sum
Two Pointers