Two Pointers Tecnique - rFronteddu/general_wiki GitHub Wiki

Typical problems

Lists and Cycles => O(n)

A classic problem is to detect if there are cycles in a list. Imagine two runners. If they are running on a circular path, a faster runner will reach the slower one (see the tortoise and hare math). To detect the node that starts the cycle, first you use the 2PT to detect if there is a cycle, then reset the slow pointer and advance both 1 step at a time until they meet again.

2PT In Linked List Template

ListNode slow = head;
ListNode fast  head;

// change condition to fit problem
while (slow != null && fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow == fast) { // fit to problem
        return true;
    }
}
return false; // fit to problem

Tips:

  • O(n+m) = O(n) where m<n is the number of steps to catch up before the two pointers meet if there are cycles.

Example: Reverse Array

2PT II

You can also use two pointers that move at different speed.

Example: Remove element from array in place, return new len

Intro

Use the two pointers technique when:

  • The input is a sorted array or can be sorted.
  • You’re looking for:
    • Pairs or subarrays with a condition (sum, difference, etc.).
    • In-place modifications (no extra space).
  • Window-like problems where ends move toward each other.
  • You need to reduce O(n²) brute force to O(n).

Typical pointer setups:

  • left at start, right at end
  • or slow and fast pointers

Ask yourself:

  • Is the array sorted or sortable?
  • Do I need:
    • Pairs?
    • In-place updates?
    • Min/max distance or area?
  • Can I move one pointer to improve the condition?

If yes → Two pointers is a strong candidate.