← DSA
EASY

Linked List Cycle

PracticeNeetCode ↗LeetCode ↗

Given the head of a linked list, determine whether the list contains a cycle — some node's next eventually points back to a node earlier in the list.

Example

Input head = [3,2,0,-4], tail connects to index 1
Output true

Key Pointers

Step-by-Step Analysis

  1. Initialize slow = head, fast = head.
  2. Loop while fast and fast.next are not None: move slow one step, fast two steps.
  3. If at any point slow is fast, a cycle exists — return True.
  4. If the loop ends because fast (or fast.next) is None, return False.

Complexity

Time: O(n) — Space: O(1)

Code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def hasCycle(head: ListNode | None) -> bool:
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

Code Explanation

How the solution above works, piece by piece.

  1. Two pointers start at the head: slow moves one step, fast two steps.
  2. while fast and fast.next: if fast reaches the end, there is no cycle.
  3. Once both are inside the cycle, the gap between them shrinks by one per step, so they can't jump past each other; they must meet.
  4. slow is fast compares node identity, not values; different nodes can hold the same value.
  5. O(n) time and O(1) space, versus O(n) space for a set of visited nodes.

Visual Walkthrough

Running it on [3, 2, 0, -4] with the tail linked to index 1:

List 3, 2, 0, -4 whose tail points back to 2320-4tail → index 1step 1: slow at 2, fast at 0step 2: slow at 0, fast at 2step 3: slow at -4, fast at -4 → same node: cycle
Slow moves 1 node per step, fast moves 2. Inside a loop, fast gains one node on slow every step, so it must land on the same node eventually. Without a loop, fast would simply reach None.
the back link

Video Explanation

NeetCode — Linked Lists, LeetCode 141