You get the head of a linked list. Return whether it has a cycle: a node whose link leads back to a node earlier in the list, so that following the links never reaches the end.
Example: 3 → 6 → 6 → 9 → 5, where the last node, 5, links back to the second 6. Following the links goes 6, 9, 5, 6, 9, 5 … forever, so the answer is yes. If 5 linked to nothing, the answer would be no.
Try it yourself first: LeetCode 141 ↗. Then step through the solution below.
Walk the list and put every node into a hash set as you pass it: the nodes themselves, not their values, since two nodes can hold one value, as the example's two 6s do. If a node is already in the set, the walk has come back to it: a cycle. If the walk reaches the end, there is none. That is O(n) time but O(n) extra space for the set.
The clue is in the words "following the links never reaches the end". With a cycle, a walk along the list goes round and round, so two walkers going round at different speeds must meet sooner or later. Without one, the faster walker reaches the end.
So walk with two variables: slow moves one node a turn, fast two. Once both are in the cycle, fast gains one node on slow every turn, so it cannot jump over it: the gap shrinks to 0 and they stand on the same node. This is Floyd's cycle detection, also called the tortoise and the hare; courses list it as the "fast and slow pointers" pattern.
The player runs the code on the example. Press → for each step: the lines it runs light up in the code.
On a phone, Full screen keeps the picture and the code on one screen.
class Node: def __init__(self, val, next=None): self.val, self.next = val, next def has_cycle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: return True return False
Now write it yourself on LeetCode 141 ↗, or go on: Invert Binary Tree →
slow and fast both start at the head, 3. Each turn slow moves one node on, fast two.slow moves to the first 6, fast to the second 6. The same value, but two different nodes: they have not met.slow moves to the second 6, fast two nodes on, to 5. They are not at the same node.slow moves to 9. fast takes the link from 5 back to the second 6, then on to 9.slow and fast are at the same node, 9: only a cycle brings fast round to slow. The answer is yes.fast gains a node a turn, so it meets slow within one lap: O(n) time, O(1) space.| Approach | Time | Space |
|---|---|---|
| Brute force: a hash set of the nodes passed | O(n) | O(n) |
| Two variables, one moving twice as fast this page | O(n) | O(1) |
slow reaches the cycle within n moves, and fast catches it within one more lap; without a cycle, fast reaches the end in n / 2 turns.fast starts at no node (∅), the loop never runs, and the answer is no.fast (∅), so the loop never runs: no.fast laps the list and meets slow within n turns.The same nodes, with the last one, 5, linking to nothing. Press → for each step.
class Node: def __init__(self, val, next=None): self.val, self.next = val, next def has_cycle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: return True return False
slow and fast both start at the head, 3. Each turn slow moves one node on, fast two.slow moves to the first 6, fast to the second 6. The same value, but two different nodes: they have not met.slow moves to the second 6, fast two nodes on, to 5. They are not at the same node.fast is at 5, the last node: the node after it is ∅, so the loop is over. No cycle: the answer is no.fast reached the end in two turns, about half as many as there are nodes: O(n) time, O(1) space.The blocks below are steps of Linked List Cycle in words, and two of them do not belong. Put the right ones in order and check: your algorithm runs on the example, on the same nodes with 5 linking to nothing, and on 4 → 7 → 4 → 1 → 8, which ends at nothing too, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.
Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.
Your algorithm
Blocks
Now write it yourself on LeetCode 141 ↗, or go on: Invert Binary Tree →
class Node: def __init__(self, val, next=None): self.val, self.next = val, next def has_cycle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: return True return FalseWhere does the cycle start? That is Linked List Cycle II (LeetCode 142). Once they meet, put one variable back at the head and move both one node a turn: they meet again exactly at the node where the cycle starts. Why: when they meet, slow has made a moves to the cycle's start and b more inside it, and fast twice as many: the same a + b plus whole laps. So a + b is whole laps, and from the meeting point a more moves lead back to the start. Still O(n) time and O(1) space.
LeetCode is a trademark of LeetCode LLC. VisiGrab is not affiliated with LeetCode or with Blind; the problems are told in our own words, with our own examples.