Skip to content
TOPIC · 13 PROBLEMS · 5 PATTERNS

Two pointers

Two indexes moving through the same data, each step ruling something out for good. It turns a check of every pair into a single pass.

How to spot a two-pointer problem

“sorted”A sorted input tells you which way to move. Too small, step the left up. Too big, step the right down.
“in place”No extra array allowed. One pointer reads, the other writes where the next kept item belongs.
“palindrome”Compare the two ends and walk inwards. The first mismatch settles it.
“triplets”Three numbers with a target sum. Fix one, then solve the pair problem on the rest.

Five patterns cover almost everything

Opposite ends

O(n)

Start one pointer at each end. Look at the pair, decide which end can never be part of the answer, and move it inwards.

Reach for it when the input is sorted or symmetric, and you are looking for a pair or comparing the ends.Go deeper: Two pointers: walking an array from both ends

Fast and slow

O(n)

One pointer takes two steps for every one the other takes. If there is a loop, the fast one laps the slow one.

Reach for it when you need to find a cycle or the middle of a linked list without extra memory.

Fix one, then pinch

O(n²)

Sort, fix the first item, and run opposite ends on everything to its right. Skip repeated values to avoid duplicate answers.

Reach for it when you need triples or quadruples that hit a target, not just pairs.Go deeper: Two pointers: walking an array from both ends

The one template to memorise

The one to know cold: two pointers closing in on a sorted array. The whole trick is the comment on each move. Get those right and the rest follows.

solution.py
def pair_with_sum(nums, target):
lo, hi = 0, len(nums) - 1
while lo < hi:
total = nums[lo] + nums[hi]
if total == target:
return [lo, hi]
if total < target:
lo += 1 # too small: the smallest can never fit
else:
hi -= 1 # too big: the largest can never fit
return []

Problems, easy to hard

Do them in order the first time
#ProblemPatternDifficultySolution
1Valid PalindromeOpposite endsEasyRead
2Move ZeroesRead and writeEasyRead
3Remove Duplicates from Sorted ArrayRead and writeEasyRead
4Merge Sorted ArrayTwo inputsEasyRead
5Squares of a Sorted ArrayOpposite endsEasyRead
6Linked List CycleFast and slowEasyRead
7Two Sum II - Input Array Is SortedOpposite endsMediumRead
8Container With Most WaterOpposite endsMediumRead
9Sort ColorsRead and writeMediumRead
10Boats to Save PeopleOpposite endsMediumRead
113SumFix one, then pinchMediumRead
123Sum ClosestFix one, then pinchMediumRead
13Trapping Rain WaterOpposite endsHardRead
Next upSliding windowBinary search