Two Pointer
Welcome to the Two Pointer section of JDCodebase! The Two Pointer technique is a powerful strategy to reduce nested loops by using two indices that move through the data structure. It's widely used for solving array and string problems efficiently.
What You’ll Learn
- When and how to apply the two pointer technique
- Solving sorted array problems with opposite-direction pointers
- Detecting pairs/triplets with specific conditions
- Avoiding unnecessary iterations and improving performance
- Handling edge cases in left/right movement logic
Common Two Pointer Patterns
Opposite Ends: Start one pointer from the start and one from the end.
Before: [1, 2, 3, 4, 6] Code: let left = 0, right = arr.length - 1; while (left < right) { let sum = arr[left] + arr[right]; if (sum === target) return [left, right]; sum > target ? right-- : left++; } After: [1, 4] (example indices)
Same Direction: Both pointers start from the beginning or end and move in one direction.
Before: [1, 1, 2, 2, 3, 3] Code: let i = 0, j = 1; while (j < arr.length) { if (arr[i] !== arr[j]) { i++; arr[i] = arr[j]; } j++; } After: Removes duplicates in-place
Try This Example
Check if a sorted array has two numbers that sum to a target.
function hasPairWithSum(arr, target) { let left = 0; let right = arr.length - 1; while (left < right) { const sum = arr[left] + arr[right]; if (sum === target) return true; sum < target ? left++ : right--; } return false; }
Input: arr = [1, 2, 4, 4], target = 8
Expected Output: true