Code

Two Pointers

Need two items in a sorted list that add up to a target? The naive way checks every pair with nested loops: O(n²). The two pointers pattern does it in one pass, O(n).

Put left at the start and right at the end:

  • sum too small? move left right (to a bigger number)
  • sum too big? move right left (to a smaller number)
  • equal? found it!
nums = [1, 3, 4, 6, 9]   # sorted!
left, right = 0, len(nums) - 1
while left < right:
    total = nums[left] + nums[right]
    ...

Each step throws away one candidate that can't possibly work, so the pointers meet after at most n steps.

The same idea checks palindromes, pointers start at both ends and walk inward comparing characters, with no reversed copy needed.

Assignment

  1. pair_with_sum(nums, target): nums is sorted. Return a tuple (a, b) of two values (at different positions, a <= b) that add to target, or None if there isn't one.
  2. is_mirror(text): return True if the text reads the same both ways, ignoring case and anything that isn't a letter or digit (use str.isalnum()). Use two pointers.