Two pointers
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Many interview problems on sorted lists have a slow answer that checks every pair and a fast one that walks two indexes toward each other. Find two numbers that add up to a target in a sorted list, watch each check rule out one value for good, and prove why no answer is ever skipped. The Software lessons "Searching: linear and binary" and "Strings: text in memory" cover indexes into a list and sorted order; "Merge sort's recurrence and counting inversions" uses the same two-finger walk to merge.
Two numbers that sum to 10
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.
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 numbers that sum to 10
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.
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²)One pointer at each end
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).
line 2: i, j = 0, len(a) - 1 i = 0 → a[0] = 1 (smallest) j = 5 → a[5] = 11 (largest) line 3: while i < j keep going while the pointers have not met every pair still possible lies between i and jToo big: drop the right end
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.
check 1: i = 0, j = 5 s = a[0] + a[5] = 1 + 11 = 12 12 > 10 → line 10: j -= 1 every partner of 11 is ≥ 1, so every sum with 11 is ≥ 12 11 can never be in the answer: one check rules out 5 pairsToo small: drop the left end
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.
check 2: i = 0, j = 4 s = 1 + 8 = 9 9 < 10 → line 8: i += 1 every partner of 1 left is ≤ 8, so every sum with 1 is ≤ 9Too big again
3 + 8 = 11, still more than 10. Same reason as before: 8 is too big for every value left. j moves left to 6.
check 3: i = 1, j = 4 s = 3 + 8 = 11 11 > 10 → j -= 1 values still in play: 3, 4, 6Too small again
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.
check 4: i = 1, j = 3 s = 3 + 6 = 9 9 < 10 → i += 1 values still in play: 4, 6Found: 4 + 6 = 10
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.
check 5: i = 2, j = 3 s = 4 + 6 = 10 == 10 line 6: return 2, 3 pair_sum([1, 3, 4, 6, 8, 11], 10) → (2, 3) two pointers: 5 checks brute force: 10 pairsWhy no answer is skipped
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.
invariant: any answer pair lies in a[i..j] start: i = 0, j = n - 1 covers the whole list s > target: a[j] + a[k] ≥ s for every k in i..j-1, so a[j] is in no answer: j -= 1 keeps it true s < target: a[i] + a[k] ≤ s for every k in i+1..j, so a[i] is in no answer: i += 1 keeps it true i == j: one value left, no pair: return None is correct this needs the list to be sortedAt most n − 1 checks
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.
the gap j - i starts at n - 1 and drops by 1 per check n = 6: at most 5 checks (brute force: 15 pairs) n = 1000: at most 999 checks (brute force: 499500) time O(n), extra memory O(1): just i, j and s list not sorted yet? sort it first: O(n log n), still far less than O(n²)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01In the sorted list [1, 3, 4, 6, 8, 11] with target 10, i = 0 and j = 5 give 1 + 11 = 12. What happens next?
12 is too big. 11 is paired with the smallest value left (1) and is still too big, so every pair with 11 is too big. Drop 11 by moving j left.
02Why is it safe to drop a[i] when a[i] + a[j] is less than the target?
Every other partner of a[i] between the pointers is ≤ a[j] (the list is sorted), so no sum with a[i] can reach the target. a[i] is in no answer.
03How many times can the while loop run on a list of 1000 numbers, at most?
The gap j − i starts at 999 and shrinks by 1 per check; the loop stops when the pointers meet. 499500 is the number of pairs brute force may check.
04You run pair_sum on the unsorted list [8, 1, 11, 3] with target 4. What is the problem?
8 + 3 = 11 is too big, so j drops 3, but 3 is half of the answer 1 + 3. The 'too big for every partner' argument only holds when the list is sorted. Sorting first costs O(n log n).
05How much extra memory does the two-pointer pair sum use, beyond the list itself?
It only keeps i, j and s, whatever the size of the list. A hash-set solution takes O(n) expected time but needs O(n) extra memory.
المسرد
- Pointer (here)
- An index into a list: a whole number saying which slot we are looking at. Not a memory address.
- Two pointers
- A pattern that keeps two indexes into a list and moves them by simple rules, often toward each other from both ends.
- Pair sum (two-sum)
- Given a list and a target, find two entries that add up to the target.
- Brute force
- Trying every possibility. For pairs in a list of n items that is n(n − 1)/2 pairs.
- Invariant
- A statement that is true before the loop and stays true after every pass. Here: any answer lies between i and j.
- Sorted
- In order from smallest to largest. The two-pointer drop rules depend on it.
- O(n) time, O(1) memory
- Work grows in step with the list's length; extra memory stays the same size however long the list is.
الملاحظات والمصادر
- 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 same pattern appears elsewhere: merge sort merges two sorted halves with two pointers (MIT 6.006 calls it the "two finger algorithm"), and a pointer at each end reverses a list or checks a palindrome in one pass. The Sliding window lesson next moves two pointers in the same direction.
- 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.
- The code is real Python 3: pair_sum([1, 3, 4, 6, 8, 11], 10) returns (2, 3) after 5 passes of the while loop. With equal values allowed it still works, because each move drops one value that has been ruled out.
- Sedgewick and Wayne, Algorithms 4th ed., §1.4 Analysis of Algorithms (2-sum, 3-sum, sorted two-list scan)
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 3: Sorting (merge with the two finger algorithm)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022)
- Python Language Reference: The while statement
- Python Sorting Techniques (sorted() returns a new sorted list)
اختبار يتاح بعد الخطوة الأخيرة.