Algorithms
Two Pointers
O(n log n) time if you need to sort first, then O(n) time for the single pass · O(1) extra space, besides the sort.
The idea, in plain English
Picture two people standing at opposite ends of a sorted line of numbered cards. They walk toward each other. If their two cards do not add up to the target yet, whoever holds the smaller card steps inward. That is the only move that can raise the sum.
How it works
- 1Make sure the list is sorted first.
- 2Put one pointer, a marker for a position, at the very start, and one at the very end.
- 3If the two values add up to the target, you are done. If the sum is too small, move the left pointer right. If it is too big, move the right pointer left. Repeat until the pointers meet.
When you'd use it
Use it to find a pair that adds up to a target sum in sorted data, or for similar problems like removing duplicates or reversing a list in place. It does the job in one pass with almost no extra memory.
Common beginner mistakes
- Forgetting to sort the list first. The pointer logic only works because sorted order tells you which side to move.
- Moving the wrong pointer, or moving both at once, and skipping past the actual answer.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Numbers: 8 2 9 1 5 6
Pair summing to 10: 1 9See it in motion
Sorted list ready. One pointer at each end — press play.
Not sure this is the right topic? See the learning paths → or where this leads →