Master the art of using two pointers to solve array and string problems efficiently. Perfect for sorted arrays, palindromes, and pair-finding problems.
When dealing with sorted arrays and need to find pairs or triplets
Checking if strings or arrays form palindromes
Finding pairs that meet specific criteria (sum, difference, etc.)
Optimizing area calculations with height constraints
Usually O(n) compared to O(n²) brute force approach
O(1) extra space - no additional data structures needed
Forgetting to handle duplicate elements properly
Sort the array first if not already sorted
Standard template for two pointers approach on sorted arrays
function twoPointers(arr: number[], target: number): number[] {
let left = 0;
let right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) {
return [left, right];
} else if (sum < target) {
left++;
} else {
right--;
}
}
return [-1, -1]; // Not found
}Using two pointers to check if a string is a palindrome
function isPalindrome(s: string): boolean {
let left = 0;
let right = s.length - 1;
while (left < right) {
// Skip non-alphanumeric characters
while (left < right && !isAlphaNumeric(s[left])) {
left++;
}
while (left < right && !isAlphaNumeric(s[right])) {
right--;
}
if (s[left].toLowerCase() !== s[right].toLowerCase()) {
return false;
}
left++;
right--;
}
return true;
}
function isAlphaNumeric(char: string): boolean {
return /[a-zA-Z0-9]/.test(char);
}Finding triplets that sum to zero using two pointers
function threeSum(nums: number[]): number[][] {
const result: number[][] = [];
nums.sort((a, b) => a - b);
for (let i = 0; i < nums.length - 2; i++) {
// Skip duplicates for first element
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
result.push([nums[i], nums[left], nums[right]]);
// Skip duplicates
while (left < right && nums[left] === nums[left + 1]) left++;
while (left < right && nums[right] === nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}Two Sum
Three Sum
Four Sum
Remove Duplicates from Sorted Array
Container with Most Water