Data Structures19 sections · 729 units
Open in Course

Problem - Linked List Cycle

Detect if a cycle exists

Given the head of a linked list, determine if the list has a cycle. A cycle exists if some node's next pointer points back to a previous node, creating a loop.

If you traverse naively, you'll loop forever. Example: 123421 \to 2 \to 3 \to 4 \to 2 (4 points back to 2) has a cycle. The naive approach uses a hash set to track visited nodes.

O(n)O(n) space. Can you detect cycles in O(1)O(1) space? Constraints: up to 10410^4 nodes.