ποΈ Day 8: Two Pointers Pattern
π§ Concept Deep Dive
The Two Pointers technique is great when dealing with sorted arrays, linked lists, or problems involving pairs, subarrays, or palindromes. It uses two pointers that move at different speeds or from different directions.
πΉ Typical Use Cases:
- Removing duplicates from a sorted array
- Checking for a pair that sums to a target
- Reversing parts of arrays or strings
- Merging sorted arrays
πΉ Strategies:
-
Start + End:
- One pointer at the beginning, one at the end
- Used for target sum, palindrome checks
-
Fast + Slow:
- Fast pointer moves faster than slow
- Used to detect cycles, remove duplicates
-
Sliding Synchronization:
- Both pointers move to track ranges or match conditions
π Example 1: Pair With Target Sum (Sorted Array)
Problem:
Given a sorted array, find two numbers that add up to a target.
Approach:
- Use
leftandrightpointers - If sum is too big, move
rightleftward - If sum is too small, move
leftrightward
function twoSumSorted(nums: number[], target: number): number[] {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const sum = nums[left] + nums[right];
if (sum === target) return [left, right];
else if (sum < target) left++;
else right--;
}
return [-1, -1];
}
// Test
console.log(twoSumSorted([1, 2, 4, 6, 10], 8)); // Output: [1, 3]Visualization:
[1, 2, 4, 6, 10]
^ ^
left right => sum = 11, too big
^ ^
left right => sum = 8 β
π Example 2: Remove Duplicates (In-place)
Problem:
Remove duplicates from sorted array in-place.
Approach:
- Slow pointer marks position for unique elements
- Fast pointer scans ahead
function removeDuplicates(nums: number[]): number {
if (nums.length === 0) return 0;
let slow = 1;
for (let fast = 1; fast < nums.length; fast++) {
if (nums[fast] !== nums[fast - 1]) {
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
// Test
const arr = [1, 1, 2, 2, 3];
console.log(removeDuplicates(arr)); // Output: 3
console.log(arr.slice(0, 3)); // [1, 2, 3]Visualization:
[1, 1, 2, 2, 3]
^ ^
slow fastπ¨ Real-world Analogy
Imagine two friends searching for a meeting spot:
- One starts from the entrance (left)
- The other from the back door (right) They keep walking until they meet at the right location β perfect for balanced conditions or symmetric data.
π Big O Complexity
| Operation | Time | Space |
|---|---|---|
| Pair sum (sorted) | O(n) | O(1) |
| Remove duplicates | O(n) | O(1) |
π§ͺ LeetCode-style Homework
Problem: Squares of a Sorted Array
Function Signature:
function sortedSquares(nums: number[]): number[];Input:
[-4, -1, 0, 3, 10]Output:
[0, 1, 9, 16, 100]Hint: Start with two pointers on both ends and fill result from the back.
π Summary
- Two pointers = elegant way to scan arrays
- Best for sorted data or symmetric conditions
- Reduces nested loops into linear scans
π¬ Up Next
βΆοΈ Day 8: Fast & Slow Pointers (Tortoise and Hare)