Given the head of a singly linked list, decide whether the list contains a cycle and return true if it does, otherwise false.
A cycle exists when some node can be reached again by repeatedly following next pointers. Internally this is described by a position that the tail links back into, but that index is not given to your function; you must detect the loop purely by traversing the nodes.
Example 1
Input: head = [3,2,0,-4], pos = 1
Output: true
The last node points back to the node at index 1 (value 2), so following next repeats forever.
Example 2
Input: head = [1], pos = -1
Output: false
A single node whose next is null has no cycle.
Constraints
The number of nodes is in the range [0, 10^4].-10^5 <= Node.val <= 10^5pos is -1 (no cycle) or a valid 0-based index into the list.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI