Two-pointer methods work when moving a pointer can discard possibilities without losing a valid answer. Explain the ordering invariant.
Before you start
You should know arrays, loops and basic complexity notation. Start with a small input you can trace by hand. State what each variable means and which invariant is maintained, then use that invariant to explain correctness before discussing performance or writing a more compact solution.
The practical goal is to reason through this situation: For a sorted pair sum, a low total moves the left pointer and a high total moves the right. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Establish sorted order
Monotonic movement decisions depend on ordered values.
Step 2: Move the justified boundary
A sum too small advances left; a sum too large decreases right.
Step 3: Preserve identity if needed
Sorting value-index pairs can retain original indices.
Worked scenario
For a sorted pair sum, a low total moves the left pointer and a high total moves the right.
For [1,2,4,7] and target 6, the outer sum is 8, so discard 7 by moving right. The sum becomes 5, so advance left; 2+4 is 6. Explain why each discarded endpoint cannot form the desired pair with remaining endpoints under sorted order.
Common mistake
Applying the same rule to unsorted input lacks the required monotonic relationship.
Verify the behavior
Test duplicates, no solution and unsorted input; document whether mutation or sorting is allowed.
Interview exercise
Preserve original indices.
Answer and reasoning
Store value-index pairs before sorting, or choose a hash-based method when retaining input order is important.
Continue learning
Compare the scenario with the Data Structures and Algorithms interview questions and test your understanding with the Data Structures and Algorithms MCQs. For terminology and implementation details, consult the reference material.