Python Snippet

Python Two-Pointer Template

Difficulty: Easy

The two-pointer pattern walks two indices through a sorted array, moving them inward (or together) based on a comparison. It turns many naive O(n^2) problems into O(n) sweeps. This entry covers the inward-sweep template (two-sum sorted), the same-direction template (remove duplicates in place), and a 3-sum builder that uses two pointers as the inner loop.

Code Snippets
/

Python Two-Pointer Template

Python Two-Pointer Template

The two-pointer pattern walks two indices through a sorted array, moving them inward (or together) based on a comparison. It turns many naive O(n^2) problems into O(n) sweeps. This entry covers the inward-sweep template (two-sum sorted), the same-direction template (remove duplicates in place), and a 3-sum builder that uses two pointers as the inner loop.

Python
Easy
3 snippets
two-pointers
algorithms
code-template
py-standard-library

930 views

4

The classic two-pointer template starts pointers at the extremes and moves them inward based on the comparison. Because the array is sorted, increasing lo strictly increases the sum and decreasing hi strictly decreases it, so each move makes monotonic progress toward the target. The total runtime is O(n) because each pointer can move at most n steps. Reach for this whenever the input is sorted and the answer involves a pair (sum, difference, product) compared against a target.