Topics

This is a classic technique where you iterate through a data-structure (commonly arrays) using two indices. These “pointers” traverse the data structure, typically in opposite directions, in the same direction, or at varying paces depending on the problem (e.g. find pairs). It’s effective for reducing time complexity from  to  or . Note that it’s often confusedwith a related technique named sliding window

When to use?

Problems that involve finding pairs, subarrays, or segments satisfying certain conditions. It can be used in conjunction with other tricks such as binary search.

Step-by-Step Framework

  • Identify the Problem Type:
    • Look for keywords like “sorted,” “subarray,” “pair,” or “sequence.”
    • Check if brute-force approaches involve nested loops (indicating potential for optimization).
  • Initialize Pointers:
  • Define Movement Conditions:
    • Move pointers based on comparisons (e.g., sum of elements vs. target).
  • Termination Condition:
    • Typically when pointers cross (opposite ends) or the fast pointer reaches the end (slow/fast).