← Back to Leo Academy Masterclass

Problem #141: Linked List Cycle

Easy Linked List

Intuition & Strategy Breakdown

Use Floyd's Cycle Finding algorithm (fast and slow pointers). Fast moves 2 steps, slow moves 1 step. If fast meets slow, a cycle exists.

Python Solution

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

Java Solution

public class Solution {
    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;
    }
}
Watch Interactive Video on Leo Academy Main App