Two Pointers Basics - aloalgo.com

Two Pointers Basics

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).

The Core Idea

Instead of checking every pair with nested loops, we use two pointers that move based on conditions. The key insight is that by making smart decisions about which pointer to move, we can skip comparisons we know won't work.Why it works: Two pointers leverages the structure of the problem—usually sorted order or some monotonic property—to eliminate unnecessary comparisons.

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

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

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

Complexity

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

Key Takeaways

  1. Identify the pattern: Determine whether you need opposite ends, same direction, or fast/slow pointers.
  2. Leverage structure: Two pointers works best when there's sorted order or a monotonic property to exploit.
  3. Think about pointer movement: The key decision is which pointer to move based on the current state.
  4. O(1) space: Two pointers typically uses constant extra space, making it memory efficient.
Was this helpful?
© 2026 aloalgo.com. All rights reserved.