The problem
A sorted list: 1, 3, 4, 6, 8, 11. Find two numbers that add up to 10. Brute force tries every pair: 6 numbers make 15 pairs, and the count grows like n². Sorted order lets us do much better.
Walking inward
A pointer here is just an index: a number saying which slot we look at. i starts at the left end, on the smallest value (1). j starts at the right end, on the largest (11).
1 + 11 = 12, more than 10. 11 pairs with the smallest value left and is still too big, so it is too big with every value. Drop it: j -= 1.
1 + 8 = 9, less than 10. 1 pairs with the largest value left and still falls short, so no partner can help it. Drop it: i += 1.
3 + 8 = 11, still more than 10. Same reason as before: 8 is too big for every value left. j moves left to 6.
3 + 6 = 9, less than 10. 3 is too small for every value left. i moves right to 4. Only two values remain between the pointers.
4 + 6 = 10, exactly the target. The function returns the two indexes, (2, 3). Five checks did the job that brute force needed 10 pair checks for.
Why it works
Each dropped value was ruled out against every value still in play, so no answer was lost. The rule, kept true at every check: if an answer exists, both its numbers lie between i and j.
Every check either returns or moves a pointer one slot inward, and the loop stops when they meet. So a list of n numbers needs at most n − 1 checks: O(n) time, and only two indexes of extra memory.
What happens
;; step 1/9 · problem a = [1, 3, 4, 6, 8, 11] (sorted, n = 6) target = 10 brute force: try every pair a[p] + a[q], p < q pairs = n(n - 1)/2 = 6·5/2 = 15 here it looks at 10 pairs before it finds (2, 3) n = 1000 → 499500 pairs: O(n²)
Two pointers needs sorted input. On an unsorted list, sort first (sorted(a) in Python returns a new sorted list); merge sort takes O(n log n) time (MIT 6.006, Lecture 3), so the whole method is O(n log n), still far less than the O(n²) of checking every pair. The function returns indexes, not values: (2, 3) means a[2] = 4 and a[3] = 6. If no pair exists, the pointers meet and it returns None.