Two Pointers Technique

intermediate30 min

Two Pointers Technique

Two pointers keep a pair of indices and move them under clear rules so you never need an O(n²) nested loop over the same data.

Types of Two Pointers

  • Opposite Directional: Pointers start from opposite ends and move toward each other
  • Same Directional: Pointers start from the same end and move in the same direction
  • Fast and Slow: One pointer moves faster than the other

Opposite Directional Example - Two Sum in Sorted Array

Same Directional Example - Remove Duplicates

Fast and Slow Pointers - Cycle Detection

// Detect cycle in linked list (Floyd's Algorithm)
public boolean hasCycle(ListNode head) {
    if (head == null || head.next == null) return false;
    
    ListNode slow = head;
    ListNode fast = head;
    
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        
        if (slow == fast) return true;
    }
    
    return false;
}

// Find middle of linked list
public ListNode findMiddle(ListNode head) {
    if (head == null) return null;
    
    ListNode slow = head;
    ListNode fast = head;
    
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    
    return slow;
}

Common Applications

  • Array Problems: Two sum, container with most water, 3 sum
  • String Problems: Palindrome check, reverse string
  • Linked List: Cycle detection, find middle, reverse
  • Optimization: Reduce time complexity from O(n²) to O(n)