DSAPatternsAlgorithms
Mastering the Two Pointer Technique
Learn when and how to use the two pointer pattern to solve array problems efficiently.
5 min read
Mastering the Two Pointer Technique
The two pointer technique is a pattern that uses two pointers to iterate through a data structure. It's incredibly versatile and efficient.
When to Use Two Pointers
- Sorted arrays
- Finding pairs with specific conditions
- In-place array modifications
- Palindrome problems
Pattern Variations
Opposite Direction
function twoSum(arr, target) {
let left = 0, right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) return [left, right];
if (sum < target) left++;
else right--;
}
return [-1, -1];
}
Same Direction (Fast/Slow)
function removeDuplicates(arr) {
if (arr.length === 0) return 0;
let slow = 0;
for (let fast = 1; fast < arr.length; fast++) {
if (arr[fast] !== arr[slow]) {
slow++;
arr[slow] = arr[fast];
}
}
return slow + 1;
}
Classic Problems
- Container With Most Water - Opposite direction
- Remove Duplicates - Same direction
- Three Sum - Two pointers + iteration
Practice these patterns until they become second nature!