From 6bfe811325cde05fe341cc71558f84f11fb9abe2 Mon Sep 17 00:00:00 2001 From: Sanat Kumar Gupta <123228827+SKG24@users.noreply.github.com> Date: Mon, 28 Oct 2024 19:27:16 +0530 Subject: [PATCH 1/2] #897 cycle detection in linked list Given the `head` of a linked list, determine if the linked list contains a cycle. A cycle exists if a node in the list points back to an earlier node, creating a loop in the list. Internally, a variable `pos` represents the index of the node that the tail's `next` pointer is connected to. If there is no cycle, `pos` is `-1`. --- .../Detect_Cycle_in_List/program.py | 54 +++++++++++++++++++ .../Detect_Cycle_in_List/readme.md | 36 +++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 Algorithms_and_Data_Structures/Linked List/Detect_Cycle_in_List/program.py create mode 100644 Algorithms_and_Data_Structures/Linked List/Detect_Cycle_in_List/readme.md diff --git a/Algorithms_and_Data_Structures/Linked List/Detect_Cycle_in_List/program.py b/Algorithms_and_Data_Structures/Linked List/Detect_Cycle_in_List/program.py new file mode 100644 index 0000000000..cf418ea079 --- /dev/null +++ b/Algorithms_and_Data_Structures/Linked List/Detect_Cycle_in_List/program.py @@ -0,0 +1,54 @@ +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def hasCycle(self, head: ListNode) -> bool: + slow, fast = head, head + + # Use Floyd's Cycle-Finding Algorithm + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + return True + return False + +# Helper function to create a linked list with a cycle +def createLinkedList(values, pos): + head = ListNode(values[0]) + current = head + nodes = [head] # store nodes to connect cycle later + + for value in values[1:]: + new_node = ListNode(value) + current.next = new_node + current = new_node + nodes.append(new_node) + + # Create cycle if pos is not -1 + if pos != -1: + current.next = nodes[pos] + + return head + +# Helper function to display the result +def printResult(head, pos): + solution = Solution() + has_cycle = solution.hasCycle(head) + print(f"Cycle at position {pos}: {'Cycle detected' if has_cycle else 'No cycle detected'}") + +# Example usage +values = [3, 2, 0, -4] +pos = 1 # means the last node connects to the node at index 1 +head = createLinkedList(values, pos) +print("Input linked list values:", values) +printResult(head, pos) + +# Test with no cycle +values_no_cycle = [1, 2] +pos_no_cycle = -1 # no cycle +head_no_cycle = createLinkedList(values_no_cycle, pos_no_cycle) +print("\nInput linked list values:", values_no_cycle) +printResult(head_no_cycle, pos_no_cycle) diff --git a/Algorithms_and_Data_Structures/Linked List/Detect_Cycle_in_List/readme.md b/Algorithms_and_Data_Structures/Linked List/Detect_Cycle_in_List/readme.md new file mode 100644 index 0000000000..a0598aedd6 --- /dev/null +++ b/Algorithms_and_Data_Structures/Linked List/Detect_Cycle_in_List/readme.md @@ -0,0 +1,36 @@ +# Linked List Cycle Detection + +## Problem Statement +Given the `head` of a linked list, determine if the linked list contains a cycle. A cycle exists if a node in the list points back to an earlier node, creating a loop in the list. Internally, a variable `pos` represents the index of the node that the tail's `next` pointer is connected to. If there is no cycle, `pos` is `-1`. + +Return `true` if the linked list has a cycle, otherwise return `false`. + +### Example + +Given the linked list: + +- **Input**: `head = [3,2,0,-4], pos = 1` +- **Output**: `true` + +### Constraints +- The number of nodes in the list is in the range `[0, 10^4]`. +- `-10^5 <= Node.val <= 10^5` +- `pos` is `-1` if there is no cycle. + +## Solution Approach + +### Floyd’s Cycle Detection Algorithm (Tortoise and Hare) +This approach uses two pointers (`slow` and `fast`) to detect a cycle: + +1. **Initialize**: + - Set `slow` and `fast` to `head`. + +2. **Traverse**: + - Move `slow` by one step (`slow = slow->next`) and `fast` by two steps (`fast = fast->next->next`) in each iteration. + +3. **Cycle Check**: + - If there’s a cycle, `slow` and `fast` will eventually meet at some point within the loop. + - If `fast` reaches the end (`NULL`), there is no cycle. + +This algorithm efficiently checks for cycles in `O(n)` time complexity with `O(1)` space complexity. + From 467a8e916b6696e7ce66cf372af1cf5870a10b74 Mon Sep 17 00:00:00 2001 From: SKG24 Date: Mon, 28 Oct 2024 14:09:57 +0000 Subject: [PATCH 2/2] updating Project-Structure.md --- Project-Structure.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Project-Structure.md b/Project-Structure.md index f727eb8f4e..57719476f4 100644 --- a/Project-Structure.md +++ b/Project-Structure.md @@ -93,6 +93,8 @@ * Linked List * Clone A List With Random Pointers * [Program](Algorithms_and_Data_Structures/Linked%20List/Clone_a_List_with_Random_Pointers/program.py) + * Detect Cycle In List + * [Program](Algorithms_and_Data_Structures/Linked%20List/Detect_Cycle_in_List/program.py) * [Menu Driven Code For Circular Doubly Linkedlist](Algorithms_and_Data_Structures/Linked%20List/Menu_Driven_Code_for_Circular_Doubly_LinkedList.py) * [Menu Driven Code For Circular Linkedlist](Algorithms_and_Data_Structures/Linked%20List/Menu_Driven_Code_for_Circular_LinkedList.py) * [Menu Driven Code For Doubly Linkedlist](Algorithms_and_Data_Structures/Linked%20List/Menu_Driven_Code_for_Doubly_LinkedList.py)