Linked List Cycle
1 approach, code in every language
Problem description
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.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free