From c623a1390fb39830eb4c5dbf1f78cb7570a91cba Mon Sep 17 00:00:00 2001 From: Mohit Joshi Date: Thu, 15 Oct 2026 02:26:57 +0530 Subject: [PATCH] Optimize linked-list loop detection Use Floyd's cycle detection algorithm to reduce has_loop auxiliary space from O(n) to O(1). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- data_structures/linked_list/has_loop.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/data_structures/linked_list/has_loop.py b/data_structures/linked_list/has_loop.py index a25204e3c4ce..06d193e2d259 100644 --- a/data_structures/linked_list/has_loop.py +++ b/data_structures/linked_list/has_loop.py @@ -37,11 +37,14 @@ def has_loop(self) -> bool: >>> root_node.has_loop True """ - try: - list(self) - return False - except ContainsLoopError: - return True + slow_node = self + fast_node = self + while fast_node and fast_node.next_node: + slow_node = slow_node.next_node + fast_node = fast_node.next_node.next_node + if slow_node is fast_node: + return True + return False if __name__ == "__main__":