Skip to main content

Two Pointers

Learn Two Pointers (Arrays, Data Structures & Algorithms) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

What is the Two Pointers Technique? Two pointers walk through data using two indices instead of one, usually moving toward each other (from both ends) or in the same direction at different speeds - turning an O(n²) nested-loop scan into O(n). Opposite ends: left = 0 , right = n-1 , move them toward the middle based on a condition. Requires the array to be sorted for most classic uses (like Two Sum on a sorted array, or reversing an array). Same direction: both pointers start at 0 and move forward at different rates (e.g. fast/slow pointer, or a read/write pointer for in-place removal).

More lessons in Arrays