A Two-Pointer approach is an algorithmic technique that uses two reference pointers to traverse a data structure (typically an array or a linked list) simultaneously. It is primarily used to optimize nested loop solutions ($O(N^2)$) down to linear time ($O(N)$) by avoiding redundant scans.
# Simple demonstration: checking if a sorted array has a pair that sums to a target
left, right = 0, len(nums) - 1
while left < right:
# Logic happens here
left += 1 # or right -= 1
Instead of scanning elements one by one using a single loop, you track two indices (pointers) that move independently or relative to each other.
By keeping track of two locations at once, you eliminate the need to run nested loops ($O(N^2)$). Most two-pointer solutions run in a single linear pass.
Since you are only storing two integer index variables (like i and j or left and right), this approach uses zero extra memory, making it highly memory-efficient.
For many two-pointer patterns (like searching for target sums), the input array must be sorted. If it is not sorted, the pointers cannot make logical decisions about which direction to move.
Depending on the problem, your two pointers will move in one of two ways:
Pointers start at the extreme opposite ends (left = 0 and right = len(arr) - 1) and move toward each other until they meet.
• Use Case: Sorted arrays, reversing strings, finding target sums, checking palindromes.