From 6228d64e7cc847cb9defdaa520789f6a0a55d413 Mon Sep 17 00:00:00 2001 From: krishna2707 Date: Sat, 17 Oct 2026 14:30:04 +0530 Subject: [PATCH] Use constant-space linked-list loop detection --- data_structures/linked_list/has_loop.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/data_structures/linked_list/has_loop.py b/data_structures/linked_list/has_loop.py index a25204e3c4ce..443a26f7593f 100644 --- a/data_structures/linked_list/has_loop.py +++ b/data_structures/linked_list/has_loop.py @@ -27,6 +27,7 @@ def __iter__(self) -> Iterator[Any]: def has_loop(self) -> bool: """ A loop is when the exact same Node appears more than once in a linked list. + Detect loops in O(n) time and O(1) auxiliary space using Floyd's algorithm. >>> root_node = Node(1) >>> root_node.next_node = Node(2) >>> root_node.next_node.next_node = Node(3) @@ -37,11 +38,14 @@ def has_loop(self) -> bool: >>> root_node.has_loop True """ - try: - list(self) - return False - except ContainsLoopError: - return True + slow: Node | None = self + fast: Node | None = self + while fast is not None and fast.next_node is not None: + slow = slow.next_node + fast = fast.next_node.next_node + if slow is fast: + return True + return False if __name__ == "__main__":