DEV Community

Dev Cookies
Dev Cookies

Posted on

πŸ’πŸ‡ Fast and Slow Pointers in Java – The Ultimate Guide

The Fast and Slow Pointer technique is a powerful approach used to solve problems involving linked lists, cycles, palindromes, and more.

Also known as Floyd's Cycle Detection Algorithm, this technique is a must-have in your interview toolkit.


πŸ“˜ What is Fast and Slow Pointer?

Two pointers are used:

  • Slow Pointer (Tortoise) – moves 1 step at a time
  • Fast Pointer (Hare) – moves 2 steps at a time

When both pointers are used on a data structure (like a linked list), their interaction can help detect cycles, find the middle, check for palindromes, and more.


🧠 Why Use This Technique?

βœ… Detect cycle in linked list

βœ… Find starting point of the cycle

βœ… Find middle of linked list

βœ… Check for palindrome

βœ… Detect intersection in linked lists


🧩 Basic Template

ListNode slow = head;
ListNode fast = head;

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

    if (slow == fast) {
        // Cycle detected
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ”¨ Java Code Examples


πŸ“˜ 1. Detect Cycle in a Linked List

public boolean hasCycle(ListNode head) {
    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;
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ If they meet, a cycle exists.

⏱ Time: O(n), 🧠 Space: O(1)


πŸ“˜ 2. Find Start of Cycle

public ListNode detectCycle(ListNode head) {
    ListNode slow = head;
    ListNode fast = head;

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

        if (slow == fast) {
            ListNode entry = head;
            while (entry != slow) {
                entry = entry.next;
                slow = slow.next;
            }
            return entry;
        }
    }
    return null;
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ After detection, move one pointer to head and move both at 1 step.

They’ll meet at cycle start.


πŸ“˜ 3. Find Middle of Linked List

public ListNode findMiddle(ListNode head) {
    ListNode slow = head;
    ListNode fast = head;

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

    return slow; // Middle node
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ If even length, returns second middle.

⏱ Time: O(n)


πŸ“˜ 4. Check if Linked List is Palindrome

public boolean isPalindrome(ListNode head) {
    ListNode slow = head;
    ListNode fast = head;

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

    // Reverse second half
    ListNode secondHalf = reverse(slow);
    ListNode firstHalf = head;

    while (secondHalf != null) {
        if (secondHalf.val != firstHalf.val) return false;
        secondHalf = secondHalf.next;
        firstHalf = firstHalf.next;
    }
    return true;
}

private ListNode reverse(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Uses fast/slow to split list, then reverse & compare.

⏱ Time: O(n), Space: O(1)


πŸ“˜ 5. Happy Number Problem (LeetCode 202)

public boolean isHappy(int n) {
    int slow = n;
    int fast = getSquare(n);

    while (slow != fast) {
        slow = getSquare(slow);
        fast = getSquare(getSquare(fast));
    }

    return slow == 1;
}

private int getSquare(int n) {
    int sum = 0;
    while (n > 0) {
        int digit = n % 10;
        sum += digit * digit;
        n /= 10;
    }
    return sum;
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Fast and slow applied on numbers instead of linked lists.

Detect cycle in digit squares.


πŸ“Š Complexity

Problem Time Space
Detect cycle O(n) O(1)
Cycle start O(n) O(1)
Find middle O(n) O(1)
Palindrome O(n) O(1)
Happy number O(log n) O(1)

πŸ’‘ Interview Questions

Problem Platform
Linked List Cycle I & II LeetCode 141, 142
Find Middle of Linked List GFG
Palindrome Linked List LeetCode 234
Intersection of Two Linked Lists LeetCode 160
Happy Number LeetCode 202

🎯 Final Thoughts

Fast and slow pointers are deceptively simple but incredibly powerful. They let you optimize your linked list solutions without extra space and are a must-know for technical interviews.

Master this pattern, and you'll unlock a whole set of problems with clean, efficient solutions. πŸš€


Top comments (0)