โ† Back to Index

๐Ÿข๐Ÿ‡ Fast and Slow Pointer โ€“ Java Cheat Sheet (One Page)

๐Ÿ“Œ What Is It?

Two pointers move at different speeds. Often used for cycle detection, midpoint finding, and palindrome logic.

๐Ÿงฑ Pattern Template

ListNode slow = head;
ListNode fast = head;

while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
}

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example 1: Detect Cycle in Linked List

public boolean hasCycle(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) return true;
    }
    return false;
}

๐Ÿงช Example 2: Find Middle of Linked List

public ListNode middleNode(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}

๐Ÿ’ก Pro Tips