The Two Pointer Technique Explained Resource - aloalgo

The Two Pointer Technique Explained

Two pointers is one of the most versatile techniques in coding interviews. The idea is simple: use two pointers to traverse a data structure, avoiding the need for nested loops. This often reduces O(n²) solutions to O(n).

1. The Three Patterns

Almost every two pointer problem falls into one of these categories:
PatternPointers StartMovementClassic Problems
Opposite EndsStart and endMove toward each otherTwo Sum (sorted), Container With Water
Same DirectionBoth at startOne fast, one slowRemove duplicates, Merge arrays
Fast & SlowBoth at startDifferent speedsCycle detection, Find middle

2. Opposite Ends Pattern

Start with pointers at both ends of a sorted array. Move them toward each other based on some condition.

Template

Two Sum (Sorted Array)

Find two numbers that add up to target in a sorted array.

Container With Most Water

Find two lines that form a container holding the most water.

Valid Palindrome

3Sum

Find all triplets that sum to zero. Fix one element, then use two pointers on the rest.

3. Same Direction Pattern

Both pointers start at the beginning. One pointer (fast) explores ahead, while the other (slow) marks a position.

Template

Remove Duplicates from Sorted Array

Move Zeroes to End

Remove Element

Merge Two Sorted Arrays

4. Fast & Slow Pointer (Floyd's)

One pointer moves twice as fast as the other. Used for cycle detection and finding midpoints in linked lists.

Detect Cycle in Linked List

Find Cycle Start

Find Middle of Linked List

Palindrome Linked List

Use fast/slow to find middle, reverse second half, compare.

5. When to Use Two Pointers

SignalPattern
Sorted array + find pairOpposite ends
Palindrome checkOpposite ends
In-place array modificationSame direction (slow/fast)
Merging sorted arraysSame direction
Linked list cycleFast & slow
Find middle of listFast & slow
Reduce O(n²) to O(n)Usually opposite ends

6. Two Pointers vs Sliding Window

They're related but different:
Two PointersSliding Window
GoalFind pair/triplet satisfying conditionFind subarray satisfying condition
Typical movementToward each other or same directionAlways same direction (right expands)
Data usuallySortedNot necessarily sorted
ExampleTwo Sum in sorted arrayLongest substring without repeats

7. Complexity

PatternTimeSpace
Opposite endsO(n)O(1)
Same directionO(n)O(1)
Fast & slowO(n)O(1)
3Sum (with sorting)O(n²)O(1)

8. Practice Problems

Opposite EndsFast & Slow (Linked List)Merging

Final Thoughts

Two pointers is really about eliminating redundant comparisons. Instead of checking every pair (O(n²)), you use the structure of the problem—usually sorted order—to skip comparisons you know won't work. The key is recognizing which direction to move each pointer based on your current state.
Was this helpful?
© 2026 aloalgo. All rights reserved.