Multiple Pointers Pattern
The Multiple Pointers pattern involves creating pointers or values that correspond to an index or position and move towards the beginning, end, or middle based on a certain condition.
What is Multiple Pointers?โ
This pattern creates pointers or values that correspond to array indices and move through the data structure in tandem or in opposite directions to find a pair of elements that match certain conditions.
When to Use?โ
- Working with sorted arrays
- Finding pairs in an array that sum to a target
- Finding unique values
- Partitioning arrays
- Detecting cycles in linked lists
Common Applicationsโ
- Two sum problems
- Three sum problems
- Finding unique values
- Removing duplicates
- Palindrome verification
Time Complexityโ
Most multiple pointers solutions achieve O(n) time complexity, compared to O(nยฒ) with nested loops.
Example Problemsโ
1. Sum Zeroโ
Problem Descriptionโ
Write a function that finds the first pair of numbers in a sorted array that sum to zero.
Exampleโ
Input: [-3, -2, -1, 0, 1, 2, 3];
Output: [-3, 3];
Input: [-2, 0, 1, 3];
Output: undefined;
Solutionโ
function sumZero(arr) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
let sum = arr[left] + arr[right];
if (sum === 0) {
return [arr[left], arr[right]];
} else if (sum > 0) {
right--;
} else {
left++;
}
}
}
Time Complexityโ
- Time: O(n)
- Space: O(1)
2. Count Unique Valuesโ
Problem Descriptionโ
Implement a function that counts unique values in a sorted array.
Exampleโ
Input: [1, 1, 1, 2, 3, 3, 4, 4, 5, 6];
Output: 6;
Input: [-2, -1, -1, 0, 1];
Output: 4;
Solutionโ
function countUniqueValues(arr) {
if (arr.length === 0) return 0;
let i = 0;
for (let j = 1; j < arr.length; j++) {
if (arr[i] !== arr[j]) {
i++;
arr[i] = arr[j];
}
}
return i + 1;
}
Time Complexityโ
- Time: O(n)
- Space: O(1)
Practice Problemsโ
To master the multiple pointers pattern, try solving these problems:
- Three Sum
- Remove Duplicates from Sorted Array
- Find Pair with Target Sum
- Dutch National Flag Problem
- Move Zeros to End
Common Multiple Pointers Strategiesโ
-
Two Pointers from Ends
- Start pointers at beginning and end
- Move inward based on conditions
-
Fast and Slow Pointers
- One pointer moves faster than other
- Used for cycle detection
-
Multiple Pointers in Same Direction
- Multiple pointers moving forward
- Used for window-like operations
Tips for Solving Multiple Pointers Problemsโ
- Consider if array needs to be sorted
- Choose appropriate pointer movement strategy
- Handle edge cases (empty arrays, single element)
- Consider pointer initialization positions
- Think about termination conditions
Common Pitfallsโ
-
Not Checking Array Boundaries
- Always ensure pointers stay within bounds
-
Incorrect Pointer Movement
- Make sure pointers move in correct direction
- Handle equal values correctly
-
Forgetting Edge Cases
- Empty arrays
- Single element arrays
- Duplicate elements