Back to Dashboard

LinkedList Cycle

Easy

Problem Statement

Given the head of a Singly LinkedList, write a function to determine if the LinkedList has a cycle in it or not.

Examples

Example 1:

  • Input: head = [3,2,0,-4], pos = 1
  • Output: true

Approach 1 Slow Fast Pointers:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        var slow = head;
        var fast = head;
        while (slow != null && fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow.equals(fast)) {
                return true;
            }
        }
        return false;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

Linked ListSlow Fast Pointers

Date

2026-02-09
View Problem Source