Linked List Cycle
Linked List Cycle is a easy linked list problem solved with the slow fast pointers pattern.
The best approach, optimal (floyd's slow and fast pointers), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from hash set of visited nodes up.
Problem
Given the head of a linked list, decide whether it contains a cycle: some node can be reached again by following next pointers.
Examples
Example 1
- Input
head = [3, 2, 0, -4], tail connects to index 1- Output
true
Example 2
- Input
head = [1], no cycle- Output
false
Constraints
- The list has
0to10^4nodes. - Follow-up: O(1) memory.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 6 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Hash set of visited nodes | O(n) | O(n) |
| Optimal (Floyd's slow and fast pointers) | O(n) | O(1) |
1Hash set of visited nodes
O(n)O(n)Remember every node visited. Seeing a node twice means there is a cycle.
- Walk the list; if the set already has the node, return true; else add it.
class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<>();
for (ListNode p = head; p != null; p = p.next)
if (!seen.add(p)) return true;
return false;
}
}class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
seen = set()
p = head
while p:
if p in seen:
return True
seen.add(p)
p = p.next
return Falseclass Solution {
public:
bool hasCycle(ListNode* head) {
unordered_set<ListNode*> seen;
for (ListNode* p = head; p != nullptr; p = p->next)
if (!seen.insert(p).second) return true;
return false;
}
};function hasCycle(head) {
const seen = new Set();
for (let p = head; p !== null; p = p.next) {
if (seen.has(p)) return true;
seen.add(p);
}
return false;
}2Optimal (Floyd's slow and fast pointers)
O(n)O(1)Move slow one step and fast two steps. If there is a cycle, fast gains one step per move inside it and must meet slow. If fast reaches null, there is no cycle.
- slow = fast = head.
- While fast and fast.next: move; if slow == fast, return true.
- Return false.
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return Falseclass Solution {
public:
bool hasCycle(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};function hasCycle(head) {
let slow = head, fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}Edge cases to test
- Empty list
- A single node pointing to itself
Hints
Hint 1
On a circular track, a faster runner eventually laps a slower one.
FAQ
What is the best time complexity for Linked List Cycle?
Optimal (Floyd's slow and fast pointers) runs in O(n) time and O(1) extra space.
Which pattern does Linked List Cycle use?
It is a linked list problem that uses the slow fast pointers pattern. Other problems with the same pattern: Middle of the Linked List, Linked List Cycle II, Find the Duplicate Number.
Is there a brute force solution for Linked List Cycle?
Yes. Hash set of visited nodes takes O(n) time and O(n) space. Remember every node visited.
Which edge cases should I test for Linked List Cycle?
Empty list; A single node pointing to itself.