Back to DSA
Two Pointers Technique Tutorial
Lesson 1 of 3: Two Pointers Fundamentals
Progress33%
Two Pointers Fundamentals
The two pointers technique is a powerful algorithmic pattern that uses two pointers to traverse data structures efficiently. It's particularly useful for array and string problems. Key Concepts: • Left-Right Pointers: Two pointers moving from opposite ends • Fast-Slow Pointers: Two pointers moving at different speeds • Same Direction: Both pointers moving in the same direction • Opposite Direction: Pointers moving towards each other When to Use Two Pointers: • Finding pairs in sorted arrays • Removing duplicates from sorted arrays • Finding palindromes • Detecting cycles in linked lists • Finding middle elements Time Complexity: O(n) - Single pass through the data Space Complexity: O(1) - Only using two pointers The key insight is to use the sorted nature of data or specific conditions to eliminate unnecessary comparisons.
Example
// Basic two pointers template
function twoPointers(arr) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
// Process current pair
if (condition) {
// Move left pointer
left++;
} else {
// Move right pointer
right--;
}
}
return result;
}
// Example: Find two numbers that sum to target
function twoSum(arr, target) {
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++; // Need larger sum
} else {
right--; // Need smaller sum
}
}
return [-1, -1]; // Not found
}
// Example usage
const arr = [2, 7, 11, 15];
const target = 9;
console.log(twoSum(arr, target)); // [0, 1] (2 + 7 = 9)
// Visualization:
// left=0, right=3: arr[0]=2, arr[3]=15, sum=17 > 9, right--
// left=0, right=2: arr[0]=2, arr[2]=11, sum=13 > 9, right--
// left=0, right=1: arr[0]=2, arr[1]=7, sum=9 = 9, found!Visualization
Array: [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] Step 1: slow=0, fast=1, nums[0]=0, nums[1]=0, same → fast++ Step 2: slow=0, fast=2, nums[0]=0, nums[2]=1, different → slow=1, nums[1]=1, fast++ Step 3: slow=1, fast=3, nums[1]=1, nums[3]=1, same → fast++ Step 4: slow=1, fast=4, nums[1]=1, nums[4]=1, same → fast++ Step 5: slow=1, fast=5, nums[1]=1, nums[5]=2, different → slow=2, nums[2]=2, fast++ Step 6: slow=2, fast=6, nums[2]=2, nums[6]=2, same → fast++ Step 7: slow=2, fast=7, nums[2]=2, nums[7]=3, different → slow=3, nums[3]=3, fast++ Step 8: slow=3, fast=8, nums[3]=3, nums[8]=3, same → fast++ Step 9: slow=3, fast=9, nums[3]=3, nums[9]=4, different → slow=4, nums[4]=4, fast++ Result: [0, 1, 2, 3, 4, _, _, _, _, _], length = 5
Exercise
Implement a function to remove duplicates from a sorted array in-place: 1. Use two pointers technique 2. Keep the array sorted 3. Return the new length 4. Don't use extra space (O(1) space complexity) 5. Handle edge cases (empty array, single element)
Lesson 1 of 3