ENع
→Two pointers
الدرس 49 · Strings and problem-solving patterns

Two pointers

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة9 خطوات5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 49 · تفاعلي
01 / 09

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²)
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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²)
  2. 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 j
  3. Too 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 pairs
  4. Too 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 ≤ 9
  5. Too 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, 6
  6. Too 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, 6
  7. Found: 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 pairs
  8. Why 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 sorted
  9. At 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²)

اختبار يتاح بعد الخطوة الأخيرة.