From 26df293171a7fd17e84eae4e1c6a10312a8ca931 Mon Sep 17 00:00:00 2001 From: Aarya Joshi Date: Sat, 17 Oct 2026 10:54:31 +0530 Subject: [PATCH] Optimize has_loop using Floyd's cycle detection Refactored has_loop method to use the Floyd's cycle-finding algorithm for detecting loops in a linked list. --- data_structures/linked_list/has_loop.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/data_structures/linked_list/has_loop.py b/data_structures/linked_list/has_loop.py index a25204e3c4ce..c92f7908139b 100644 --- a/data_structures/linked_list/has_loop.py +++ b/data_structures/linked_list/has_loop.py @@ -37,11 +37,17 @@ def has_loop(self) -> bool: >>> root_node.has_loop True """ - try: - list(self) - return False - except ContainsLoopError: - return True + slow = self + fast = 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__":