Two Pointers

Find two numbers that add up to a target in a sorted list, with one pointer at each end moving towards the other.

Python · intermediate · 6 min · 28 steps · free

What you'll learn

two_pointers.py

def pair_with_sum(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return (nums[left], nums[right])
        if total < target:
            left += 1
        else:
            right -= 1
    return None

print(pair_with_sum([1, 3, 4, 6, 8, 11], 10))

Step by step

  1. Python defines the function pair_with_sum(). Its body does not run yet: it runs each time the function is called.
  2. Python calls pair_with_sum(), with nums = [1, 3, 4, 6, 8, 11] and target = 10. It gets its own names.
  3. left is created with the value 0. right is created with the value 5.
  4. left < right is true, so the loop body runs.
  5. The smallest plus the largest: 1 + 11 = 12.
  6. total == target is false, so the block under it is skipped.
  7. total < target is false, so the block under it is skipped.
  8. 12 is too big, so the largest number cannot be part of the answer: move right left.
  9. left < right is true, so the loop body runs.
  10. total changes from 12 to 9.
  11. total == target is false, so the block under it is skipped.
  12. total < target is true, so the block under it runs.
  13. 9 is too small: move left right, to a bigger number.
  14. left < right is true, so the loop body runs.
  15. total changes from 9 to 11.
  16. total == target is false, so the block under it is skipped.
  17. total < target is false, so the block under it is skipped.
  18. right changes from 4 to 3.
  19. left < right is true, so the loop body runs.
  20. total changes from 11 to 9.
  21. total == target is false, so the block under it is skipped.
  22. total < target is true, so the block under it runs.
  23. left changes from 1 to 2.
  24. left < right is true, so the loop body runs.
  25. total changes from 9 to 10.
  26. total == target is true, so the block under it runs.
  27. 4 + 6 = 10: found it.
  28. pair_with_sum() has finished, so its names are gone. It prints (4, 6).

Common mistakes

Best practices

Key takeaways

Check yourself

Checking every pair instead costs?

Answer: O(n²)

Two pointers here needs the list to be?

Answer: Sorted

·

More in Complexity and Searching