Stage 1 · Code
Two Pointers & Sliding Window
Opposite-End Pointers
Sorted array + two ends converging inward — the pattern behind Two Sum II, 3Sum, and Container with Most Water.
The Pattern
Place one pointer at each end of a sorted array. Move the left pointer right to increase the sum, move the right pointer left to decrease it. Each step eliminates one candidate, giving O(n) total instead of O(n²) brute force.
Two Pointers — target: 9
Step 1 / 2 — lo=0, hi=5
nums[0] + nums[1] = 2 + 7 = 9 ✓
def two_sum_sorted(nums: list[int], target: int) -> list[int]:
"""Find pair summing to target in sorted array (1-indexed)."""
l, r = 0, len(nums) - 1
while l < r:
total = nums[l] + nums[r]
if total == target:
return [l + 1, r + 1] # 1-indexed
elif total < target:
l += 1 # need larger sum → move left right
else:
r -= 1 # need smaller sum → move right left
return []
# Usage
print(two_sum_sorted([2, 7, 11, 15], 9)) # [1, 2]
print(two_sum_sorted([-1, 0, 1, 2], 1)) # [2, 4]The invariant is: left pointer never needs to go back (elements are sorted, moving left only makes sums smaller).
Problems
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.