Linked List Cycle
Detailed guide and Python implementation for the 'Linked List Cycle' problem.
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 input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Lists
Learn everything about Python lists. Discover how to create, slice, modify, and iterate through arrays in Python natively.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python List Methods
Quick reference guide for Python list operations. Master appending, inserting, removing, sorting, and slicing elements.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.