compare_arrows

Two Pointers
Curriculum

A structured path to mastering the two pointers pattern. Redefine efficiency with two simultaneous thinkers.

What This Pattern Is Really About

directions_runSingle Pass

Reduces nested loops by maintaining two positions and moving them based on a decision rule. O(n) is the new normal.

auto_fix_highElimination

Each pointer movement eliminates possibilities that cannot be better than what remains. Search smart, not hard.

data_objectProperties

Elimination is valid when data has specific properties—usually sortedness—guaranteeing impossible outcomes.

energy_savings_leafEfficiency

Achieves O(n) time (each element visited once) and O(1) space (only track positions). Minimal footprint.

Mental Model & Invariant

Two pointers is a shrinking boundary.

"The region between your pointers contains all remaining possibilities; everything outside has been proven irrelevant."

The Core Invariant
Every valid solution either lies between the current pointer positions or has already been found.

Break this, and you lose the proof of correctness.

verified

When It Holds

Before you start, after each movement, and at termination. If false, your algorithm is incorrect.

gavel

Decision Rule

Determines which pointer moves. Must guarantee eliminated region cannot contain better solution.

flag

Termination

When pointers meet or cross, you've examined all possibilities and either found all solutions or determined none exist.

When to Think "Two Pointers"

sensorsStrong Signals

draw

Array or string is sorted

draw

Pairs or triplets with target property

draw

Compare from opposite ends

draw

Partitioning or rearranging in place

draw

Longest/shortest sequence with constraint

draw

Merging or comparing sorted sequences

ruleConstraint Signals

lock_clock

Must solve in linear time

lock_clock

Must use constant extra space

lock_clock

Cannot use additional data structures

lock_clock

Single pass through data required

Variants You Must Master

swap_horiz

Opposite Direction

Start at opposite ends and move toward each other.

// Invariant
Solutions lie between current positions.
Two sumContainerPalindrome
running_with_errors

Fast–Slow

Both move same direction at different speeds.

// Invariant
Slow marks boundary of valid elements.
DuplicatesZeroesPartition
view_sidebar

Sliding Window

Dynamic window expands and contracts.

// Invariant
Window satisfies constraint trackably.
SubstringMin windowMax sum
account_tree

Multi-Array

One pointer per array, advance by logic.

// Invariant
Unprocessed ahead of pointers.
MergeIntersectionMedian

How to Learn This Pattern

1

Identify the Invariant

Write down what must remain true at every step. What region contains all valid solutions? What does each pointer represent?

2

Define the Decision Rule

Determine when to move each pointer. What condition triggers left? Right? Why does this guarantee safe elimination?

3

Trace through by hand

Use a small example and manually execute your decision rule. Verify the invariant holds at each movement.

4

Verify Termination

Prove your algorithm finishes. Show at least one pointer moves closer to termination each step.

5

Check Edge Cases

Trace empty input, single element, duplicates, and boundaries. Verify the invariant holds.

6

Write Code

Translate your decision rule into code. If struggling, return to the invariant definition.

Canonical Problem List

Common Mistakes

error_outline

Skipping the Invariant

Failure Mode

Off-by-one errors, incorrect termination, pointer movements that violate constraints.

Mastery Fix

Write down the invariant in plain English before writing any code.

error_outline

Moving the Wrong Pointer

Failure Mode

Breaks the invariant; skips valid solutions or examines invalid regions.

Mastery Fix

Define the rule precisely: 'Move left if X, move right if Y'.

error_outline

Forgetting Edge Cases

Failure Mode

Works on happy path but fails with duplicates, empty input, or boundaries.

Mastery Fix

Trace through empty input, single element, and all duplicates first.

error_outline

Incorrect Termination

Failure Mode

Loop exits too early or too late; misses solutions or examines irrelevant regions.

Mastery Fix

Prove that at least one pointer moves closer to termination with each step.

error_outline

Assuming Sorted Input

Failure Mode

Decision rule relies on sortedness but problem doesn't guarantee it.

Mastery Fix

Verify the property or sort the input first. 'Two pointers != Sorted' always.

Interview Guidance

Interview Protocol

What they test

  • Decision Rule Justification
  • Invariant Articulation
  • Step-by-Step Tracing clarity

Strategy

Avoid "I'll use two pointers" without context. Instead: "I need to find pairs efficiently, so I'll maintain two positions and move them based on a specific rule that eliminates bad candidates."

The Verbal Template

Invariant

"At every step, [property about pointers and search space] remains true."

Decision

"I move left when [condition] and right when [condition] to eliminate safe regions."

Trace

"Let's walk through this example. Here I check X, so I move Y pointer."

Prove

"When characters cross, all possibilities are exhausted."

When You've Mastered It

done_all

Immediate pattern identification

done_all

Invariant articulated before code

done_all

Verified edge cases analytically

done_all

Zero hesitation in decision rule

done_all

Adapting to problem variations

done_all

Flawless first-try implementation

What This Unlocks Next

layers

Sliding Window

Extends boundary movement with window state tracking (contraction/expansion).

divide

Binary Search

Same elimination logic, but divides the space instead of shrinking it linearally.

rocket_launch

Greedy Algorithms

Embodying locally optimal choices for global results.

hub

Graph Traversal

Applying fast/slow pointer logic for cycle detection and connectivity.