Imagine you're following a chain of connected nodes, where each node points to the next one. But what if this chain secretly loops back on itself? ๐
Given the head of a linked list, your mission is to detect if there's a cycle - meaning you could theoretically follow the next pointers forever and end up visiting the same node again.
What makes this tricky? You can't see the entire structure at once, and you don't know where the cycle might begin (if it exists). You can only follow the next pointers one by one.
Return true if there's a cycle, false otherwise.
Note: The parameter pos mentioned in examples is just for illustration - it's not actually passed to your function.
Input & Output
Visualization
Time & Space Complexity
We visit each node exactly once, and hash set operations are O(1) on average
In worst case (no cycle), we store all n nodes in the hash set
Constraints
- The number of nodes in the list is in the range [0, 104]
- -105 โค Node.val โค 105
- pos is -1 or a valid index in the linked-list
- Follow up: Can you solve it using O(1) memory?