Two Pointers: Opposite Ends Resource - aloalgo

Two Pointers: Opposite Ends

Start with pointers at both ends of a sorted array. Move them toward each other based on some condition. This pattern is perfect for problems where you need to find pairs that satisfy a condition.

Template

Two Sum (Sorted Array)

Find two numbers that add up to target in a sorted array.
Why it works: If the sum is too small, moving the left pointer right increases the sum. If too large, moving the right pointer left decreases it. Since the array is sorted, we're guaranteed to find the pair if it exists.

Container With Most Water

Find two lines that form a container holding the most water.
Why move the shorter line? The area is limited by the shorter line. Moving the taller line inward can only decrease the area (smaller width, same or smaller height). Moving the shorter line gives us a chance to find a taller line.

Valid Palindrome

Check if a string is a palindrome, considering only alphanumeric characters.
Key insight: Compare characters from both ends moving inward. If they ever don't match, it's not a palindrome.

3Sum

Find all triplets that sum to zero. Fix one element, then use two pointers on the rest.
Pattern: Reduce 3Sum to 2Sum by fixing one element and using two pointers for the remaining two. Careful duplicate handling avoids repeated triplets.

Trapping Rain Water

Calculate how much water can be trapped between bars.
Key insight: Water at any position is determined by the minimum of the max heights on either side. By processing from the shorter side, we always know the limiting factor.

Practice Problems

Was this helpful?
© 2026 aloalgo. All rights reserved.