Skip to content

Commit 6228d64

Browse files
committed
Use constant-space linked-list loop detection
1 parent 25c712f commit 6228d64

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

‎data_structures/linked_list/has_loop.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ def __iter__(self) -> Iterator[Any]:
2727
def has_loop(self) -> bool:
2828
"""
2929
A loop is when the exact same Node appears more than once in a linked list.
30+
Detect loops in O(n) time and O(1) auxiliary space using Floyd's algorithm.
3031
>>> root_node = Node(1)
3132
>>> root_node.next_node = Node(2)
3233
>>> root_node.next_node.next_node = Node(3)
@@ -37,11 +38,14 @@ def has_loop(self) -> bool:
3738
>>> root_node.has_loop
3839
True
3940
"""
40-
try:
41-
list(self)
42-
return False
43-
except ContainsLoopError:
44-
return True
41+
slow: Node | None = self
42+
fast: Node | None = self
43+
while fast is not None and fast.next_node is not None:
44+
slow = slow.next_node
45+
fast = fast.next_node.next_node
46+
if slow is fast:
47+
return True
48+
return False
4549

4650

4751
if __name__ == "__main__":

0 commit comments

Comments
 (0)