Blueprints · Two Pointers

Two Pointers: Find a Pair With a Target Sum in a Sorted Array

One problem, three stages: make it work, make it fast, make it lean. Step through each stage in the visualizer, then run all three on a big input in the benchmark and watch the brute force overheat.

The real-world version

A payments service keeps settled amounts sorted. Reconciliation needs to know whether two settlements add up exactly to a disputed total, across millions of rows, without loading a second copy into memory.

The problem

Given a sorted array of integers nums and an integer target, return the indices of two different elements that add up to target, or None if no pair exists.

nums = [1, 4, 6, 9, 13, 17, 22], target = 19  →  (2, 4)   # 6 + 13

X-ray: watch it run

Benchmark: will the forge overheat?

Run all three stages on a large input in your browser and compare the work each one does.

In the interview

Say out loud why moving a pointer is safe ("nums[l] can't pair with anything, because nums[r] is the largest value left"). Interviewers are listening for that proof, not just the code.