nums = [1, 2, 4, 6, 7], target = 9True2 + 7 = 9
Track two positions in an array or string and move them according to a rule. The pointers can move toward each other or in the same direction, often avoiding a nested loop.
Imagine putting one finger at each end of a word. Compare the letters under your fingers, then move both fingers toward the middle. Each finger is a pointer: it remembers a position.
The key idea
Here we check whether LEVEL reads the same forward and backward. Other tasks use different movement rules; two pointers can also travel in the same direction.
Given an ascending sorted integer array and a target, return True if two values at different indices add up to the target. Otherwise, return False.
Duplicates and negative numbers are allowed. You cannot reuse one element. Fewer than two elements means False.
nums = [1, 2, 4, 6, 7], target = 9True2 + 7 = 9
nums = [1, 2, 4, 6, 9], target = 8True2 + 6 = 8
nums = [1, 2, 4, 6, 7] · target = 9
With n numbers, there are n(n − 1)/2 possible pairs. Checking all of them takes O(n²) time in the worst case.
Only loop indices are stored. No extra array is created.
nums = [1, 2, 4, 6, 9] · target = 8
Why it works: sorted order lets us rule out one number at each step. When the sum is too small, the left number cannot work with any remaining partner. When it is too large, the right number cannot work with any remaining partner.
Use an array sorted in ascending order for two pointers.
Each step moves one pointer inward. There are at most n − 1 comparisons, so the worst-case time grows linearly with the array size.
Only two indices and the current sum are stored. No extra array is needed.
Compared with brute force, two pointers skips pairs that cannot work. For sorted input, it improves worst-case time from O(n²) to O(n), while keeping extra space at O(1).