Two pointers iterate through the data structure in tandem until one or both of the pointers hit a certain condition.
Two pointers are needed because with just pointer, you would have to continually loop back through the array to find the answer, giving O(n²) time.
Usually this approach is of O(n) time complexity.
When to use
- Input is an Array or Linked List.
- Find pairs/triplets with certain sums.
- Detect cycles.
- Check palindromes.
- Compare two elements.
- Optimizing a nested loop solution to O(1) solution
- Move an element from one position to another in an array
- Searching pairs in a sorted array or linked list
- Optimizing comparisons to get better than O(n²) time
- Find a set of elements that fulfill certain constraints
- The set of elements in the array is a pair, a triplet, or a subarray
- Find intersections between two data structures
- Find middle of a linked list.
- Find cycle in linked list.
Methodology
- A single loop with two pointers within the loop
int j = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] != nums[j]) {
...
}
}
Forms
Front & Back
- Sort the array (if order doesn’t matter)
- One pointer starts from the front of the array
- The other pointer starts from the back of the array
- Moving inward depending on the sum or condition
- Usually stopping the loop before both pointers equal one another
while(left < right)
while(right > left)
Slow & Fast (Floyd’s Cycle Detection)
- One pointer starts from the first element, this is the slow pointer
- The other pointer starts from the second element, this is the fast pointer
- Fast pointer usually moves 2x as the slow
- The fast pointer is incremented to look ahead in the data structure to find the next element we want use
- Compare with the element at the slow pointer
- Replace the element at the slow pointer
Examples
- Dealing with a loop in a linked list or array
- Need to know the position of a certain element or the overall length of a linked list.
- Moving elements ahead in an array
- Trying to determine if a linked list is a palindrome
- Dealing with cyclic linked lists or arrays.