~/problems / Two pointers

Basics: pair sum in a sorted list (pointers from both ends)

easy basics ~10 min

Write pair_sum_sorted(nums: list[int], target: int) -> tuple[int, int] | None.

nums is sorted in non-decreasing order. Return (i, j), 0-based with i < j, such that nums[i] + nums[j] == target. If several pairs work, any one is accepted. If none exists, return None.

pair_sum_sorted([1, 3, 4, 6, 9], 10)   # (0, 4) or (2, 3)
pair_sum_sorted([2, 2, 5], 4)          # (0, 1)
pair_sum_sorted([1, 2, 3], 7)          # None
  • 0 <= len(nums) <= 3 * 10^5; values and target are in [-10^9, 10^9].
  • Must be O(n) time and O(1) extra space: no nested loops, and no set or dict. The tests include a large case with no answer, where trying every pair would take far too long.
Show hint

start with lo at the left end and hi at the right; if the sum is too small, only moving lo right can raise it, and if it's too big, only moving hi left can lower it.

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc