Two pointers
Two pointers is a technique that walks a slice with two indices — often from both ends, or a slow and a fast pointer — to get an O(n) pass instead of a nested O(n²) scan.
Detailed Explanation
The idea is to replace "for each i, scan j" with two indices that only move forward (or toward each other). Because each index walks the slice at most once, the time is O(n) and the extra space is O(1) besides the input.
The inward pair: a sorted slice, you want two numbers that sum to a target. Start lo at 0 and hi at len - 1. If the sum is too small, increment lo. If it is too large, decrement hi. You never need a nested loop. This needs sorted data; sort first if you must, and then the total is O(n log n).
The chase pair: one pointer writes, one reads. retain-shaped filters: read every element, write the ones you keep to the write pointer, then truncate. Rust's Vec::retain is this algorithm. Partitioning (split_at after a partition) is the same family.
The fast/slow pair: cycle detection on a linked list (Floyd), or finding the middle in one pass. Fast moves two nodes, slow moves one. When fast hits the end, slow is at mid. When they meet, there is a cycle.
In Rust you will fight the borrow checker if both pointers are &mut into the same slice. Use indices, or split_at_mut to get two disjoint mutable subslices, or swap. Indices are the usual interview-to-Rust translation: xs[i] and xs[j] with i and j as usize.
When you reach for two pointers: sorted-pair problems, in-place filters, palindrome checks, merging two sorted slices. When you reach for a hash set: the unsorted two-sum that must stay O(n). When you reach for a nested loop: n is tiny and the code is clearer.
Code Examples
fn two_sum_sorted(xs: &[i32], target: i32) -> Option<(i32, i32)> {
let mut lo = 0;
let mut hi = xs.len().checked_sub(1)?;
while lo < hi {
let sum = xs[lo] + xs[hi];
if sum == target {
return Some((xs[lo], xs[hi]));
} else if sum < target {
lo += 1;
} else {
hi -= 1;
}
}
None
}
fn main() {
println!("{:?}", two_sum_sorted(&[1, 2, 4, 7], 6)); // prints: Some((2, 4))
}Common Gotchas
Unsorted two-sum is a different algorithm
The inward-pointer version is wrong if the slice is not sorted. Hash the complements, or sort a copy first.
Two `&mut` pointers into one slice will not compile
Use indices, `split_at_mut`, or `swap`. Do not `unsafe` a second mutable pointer.
`retain` is the write-pointer pattern
Prefer it to a hand-rolled compacting loop unless you are writing the loop for study.
Off-by-one at `lo < hi` versus `lo <= hi`
When `lo == hi` you are on one element. Pair problems usually want `lo < hi`.