Linked List Cycle Detection
Medium
data-structures
Google
Meta
Microsoft
Given a singly linked list represented as a list of (value, next_index) tuples (where next_index is the index of the next node or -1 for the end), determine if it contains a cycle.
Example
# 0 -> 1 -> 2 -> 3 -> 1 (cycle)
has_cycle([(1, 1), (2, 2), (3, 3), (4, 1)])
# => True
# 0 -> 1 -> 2 (no cycle)
has_cycle([(1, 1), (2, 2), (3, -1)])
# => False
Test Cases
Python Editor
Output
Click "Run" to see results...