Two Pointers for a Sum in Sorted Data
For two distinct positions in a sorted list, comparing the sum of the smallest and largest remaining entries can eliminate one endpoint.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a target
For 1, 3, 5, 8 and target eight, the endpoint sum is nine. Keeping 8 with any remaining larger left value cannot help, so move the right endpoint to 5. The sum is then six, so move the left endpoint to 3. The sum is eight.
State the assumption
The elimination argument needs the list's nondecreasing order as a precondition. If the endpoints meet, no pair of distinct indices remains. Compare the lookup-map alternative on unsorted inputs.[1]
Rule out an endpoint using the sorted order
Find a sum of fourteen in sorted values [2, 4, 7, 10, 15]. At first, two plus fifteen is too large. Every remaining left value is at least two, so fifteen cannot form the target with any of them. Move the right pointer inward. See front-and-back scans.
(2,15): sum 17, discard 15
(2,10): sum 12, discard 2
(4,10): sum 14, return positions 1 and 3
Check the same position is never used twice
Stop once left reaches right. Test a target twice one stored value with no duplicate, then with two copies. If unsorted input is accepted, preserve original indices when sorting or choose a different method.