Opposite Ends
When To Use
Use this when two pointers start at opposite ends and each move has a local reason to discard one side.
Base Template
l = 0
r = n - 1
while l < r:
inspect l and r
move l or r based on what can be discardedSorted Pair Scan
Use this when the array is sorted and moving l or r changes the condition
monotonically.
while l < r:
if condition is too small:
l++
else if condition is too large:
r--
else:
update answer
move one or both pointersTwo Sum II
Problem: find two numbers in sorted array whose sum is target.
Pattern: move l if sum is too small, r if too large.
Applied pseudocode:
l = 0
r = n - 1
while l < r:
sum = nums[l] + nums[r]
if sum == target:
return [l, r]
else if sum < target:
l++
else:
r--Container With Most Water
Problem: maximize area between two lines.
Pattern: move the pointer with smaller height.
Boats to Save People
Problem: pair lightest and heaviest people under a weight limit.
Pattern: sorted greedy from both ends.
Fixed Index + Pair Scan
Use this when an outer loop fixes part of the answer and the remaining part is a sorted two-pointer pair scan.
sort nums
for fixed index:
l = fixed + 1
r = n - 1
while l < r:
move l or r
update answerValid Triangle Number
Problem: count triplets that can form a triangle.
Pattern: sort, fix largest side, then count pairs whose sum is greater.
Applied pseudocode:
sort nums
ans = 0
for k = n - 1 down to 2:
l = 0
r = k - 1
while l < r:
if nums[l] + nums[r] > nums[k]:
ans += r - l
r--
else:
l++3Sum
Problem: find unique triplets whose sum is 0.
Pattern: sort, fix one index, then run opposite-end two pointers.
4Sum
Problem: find unique quadruplets whose sum is target.
Pattern: sort, fix two indices, then run opposite-end two pointers.
Count Pairs Whose Sum Is Less Than Target
Problem: count pairs with sum below target.
Pattern: if nums[l] + nums[r] < target, all pairs l..r-1 with r work.
3Sum Smaller
Problem: count triplets with sum less than target.
Pattern: fix one index, then count valid opposite-end pairs.
Mirror Compare
Use this when comparing or modifying symmetric positions.
while l < r:
if s[l] and s[r] do not match:
handle mismatch
l++
r--Valid Palindrome
Problem: check if a string is a palindrome after ignoring non-alphanumeric chars and case.
Pattern: skip invalid chars, then compare mirrored chars.
Applied pseudocode:
l = 0
r = n - 1
while l < r:
while l < r and s[l] is not valid:
l++
while l < r and s[r] is not valid:
r--
if lower(s[l]) != lower(s[r]):
return false
l++
r--
return trueValid Palindrome II
Problem: check if a string can become a palindrome after deleting at most one char.
Pattern: on mismatch, try skipping either side once.
Reverse String
Problem: reverse a char array in-place.
Pattern: swap mirrored chars.
Squares of a Sorted Array
Problem: return sorted squares from a sorted array.
Pattern: compare absolute values at both ends and fill from the back.