All Patterns
👆👆
easyPattern #02
Two Pointers
Use two indices to scan from both ends or at different speeds.
What is this pattern?
Two pointers places one pointer at the start and one at the end (or both at the start moving at different speeds). It is ideal when the array is sorted or you need to find pairs satisfying a condition — eliminating one full loop from a brute-force approach.
When to use it
- Array or string is sorted (or can be sorted)
- Looking for a pair, triplet, or partition
- Need to remove duplicates or reverse in-place
- Keywords: "two sum", "palindrome", "partition", "opposite ends"
Key Insight
Move the left pointer right when the current sum is too small, move the right pointer left when too large. The sorted order guarantees you never need to revisit elements.
Java Template
Template.java
// Opposite-direction two pointers (sorted array)
int left = 0, right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
// found pair
left++; right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
// Same-direction two pointers (in-place remove)
int slow = 0;
for (int fast = 0; fast < nums.length; fast++) {
if (nums[fast] != val) {
nums[slow++] = nums[fast];
}
}