Two-Pointer Technique
A programming trick that works on arrays.
- Why it works?
- It utilizes properties of the problem, e.g. when targeting a fixed sum, increasing
aimplies decreasingb(3-sum and container-with-most-water) - It provides detailed control over iteration, e.g. skipping duplicates in 3-sum
- It utilizes properties of the problem, e.g. when targeting a fixed sum, increasing
- The keys?
- Sorting the original array is often helpful
- Find the pattern required by the problem.
- Determine how to advance the pointers. In an optimization problem such as container-with-most-water, the suboptimal value should be replaced.