Back to DSA

Linked List Cycle

easy
Acceptance: 59%
Linked List

Given the head of a singly linked list, determine whether the list contains a cycle. A cycle exists when following the links from some node eventually leads back to a previously visited node, forming a loop.

Examples

Example 1:
Input:head = [5,8,2,-1], pos = 2
Output:true
Example 2:
Input:head = [4], pos = -1
Output:false

Hints

00:00
class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) return true;
        }
        return false;
    }
}
Time complexityO(n)
Space complexityO(1)