Linked List Cycle
Learn how to solve the 'Linked List Cycle' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
The input is given as a list of values and an integer pos (the index where the tail connects to, -1 if no cycle). Implement a function hasCycle(head: list, pos: int) -> bool.
- •The number of nodes in the list is in the range [0, 10000]
- •-100000 <= Node.val <= 100000
- •pos is -1 or a valid index in the linked list
Examples
[3,2,0,-4], 1
True
There is a cycle: the tail node (-4) connects back to the node at index 1 (value 2).
[1,2], 0
True
There is a cycle: the tail node (2) connects back to the node at index 0 (value 1).
[1], -1
False
There is no cycle in the list.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.