The Two-Pointers Technique is a simple yet powerful strategy where you use two indices (pointers) that traverse a data structure—such as an array, list, or string—either toward each other or in the same direction to solve problems more efficiently.

However, two pointers vary from Sliding Window in implementations like Fast and Slow Pointers. These pointers could also start at the ends of an array and move inwards.

Identification

Use for:

  1. Sorted inputs to find pairs or ranges
  2. When a problem asks about two elements, subarrays, or ranges instead of working with a single element
  3. Sliding window problems, like maintaining a window that grows and shrinks
  4. Linked-list questions, finding cycles, finding the middle node, checking palindromes etc

Steps for Solving

  1. Determine the relationship between the two positions
    1. Comparing two elements
    2. Matching two elements
    3. Shrinking or growing based on a pair
    4. Optimize something based on two-ends
  2. Decide pointer direction
    1. Opposite ends moving inwards
    2. Same direction
    3. Cross matching
  3. Determine movement rule (when to move pointers)
    1. Movement needs to be monotonic, never move a pointer backwards