Linked List Cycle
Easy · Linked Lists · Linked List · Two Pointers
Problem
Given the head of a linked list, return whether it contains a cycle — that is, whether some node's next leads back to a node already visited.
Solve it in constant extra space.
Examples
Input: 3 -> 2 -> 0 -> -4, with the tail linked back to index 1 Output: True
The tail points at the node holding 2.
Input: 1 -> 2, no cycle Output: False
Constraints
- 0 <= nodes <= 10^4
- -10^5 <= Node.val <= 10^5
Approaches
- Set of visited nodes — time O(n), space O(n)
Follow-up
Can you solve it using O(1) (constant) memory?
Related problems
Start free on Cariara · Coding problems · System design studio