DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Pattern: Slow fast pointer

If we use slow and fast pointer at some point fast pointer and slow pointer will point to the same node.
Example: Detect cycle in the graph

public class Solution {
    public boolean hasCycle(ListNode head) {
         if(head ==null || head.next ==null) return false;
        ListNode slow = head;
        ListNode fast = slow.next;
        while(fast!=null){
            if(slow ==fast) return true;
            slow = slow.next;
            fast = fast.next ==null ? null : fast.next.next;
        }
        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)