{"id":1060,"date":"2023-12-16T06:56:38","date_gmt":"2023-12-16T06:56:38","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1060"},"modified":"2023-12-18T08:53:19","modified_gmt":"2023-12-18T08:53:19","slug":"detect-linked-list-cycle","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/detect-linked-list-cycle\/","title":{"rendered":"Linked List Cycle Detection (C++, Java, Python)"},"content":{"rendered":"\n<p>Linked lists are the fundamental data structure that provides a dynamic way to store and organize data and one of the problems of linked lists is detecting a cycle in a linked list. In this article, we will discuss the concept of a linked list cycle, and how to detect a cycle or loop in a linked list.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the Linked List Cycle Problem?<\/strong><\/h2>\n\n\n\n<p><strong>In the Linked List Cycle problem, we are given a linked list and we have to detect a cycle in this linked list, a linked list cycle occurs when a node in the list points to a previous node, creating a loop within the structure<\/strong>.<\/p>\n\n\n\n<p>Let us understand it better with an example:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/ljiD38qnuA7lcPjNbZELsf1sCwuzkECfginKmYCRiU-tHMICuU7k9zsU-8Th_HmA9RoAWYBYkfr_N_djvzNAUfOLNRyFzDTtWU0ls-szaXsxTl9Qh0086Knpan8aOlOmmq5ZHo_4bLFMIDgLfzkMTxg\" alt=\"Example of Linked List\"\/><\/figure>\n<\/div>\n\n\n<p>In the above-linked list, there is a cycle where the last node is connected to the previous node.<\/p>\n\n\n\n<p>Learning about linked list cycles is important for building a strong foundation in computer science. It hones problem-solving skills and provides practical knowledge that can be applied in various real-world scenarios.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Using Hashing to Find Linked List Cycle<\/strong><\/h2>\n\n\n\n<p>In this approach we will use a set data structure because a set data structure only stores unique nodes, if there is any cycle then we will get to know through this set data structure.<\/p>\n\n\n\n<p>Here are the steps to solve the problem using this naive approach:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Firstly we will declare a set data structure to store unique nodes.<\/li>\n\n\n\n<li>Now we will start iterating through the list and check if the node is already present in the set or not if it is already present in the set that means there is a cycle&nbsp;<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/gPaWXWUZEos4wOCqp9Otwfs3qM-N_XFAdg7VlTt7MLtgEzd4IM2cu_zdUMSuruc8fDtWaXSct182vG_9gLUV0eDqmLtLp48kQCpZZGoroyGod_uMm4QLr1hNreNFsmdzemW1qFwB0BdHtEhV6D4MEUk\" alt=\"1st Node\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Let&#8217;s implement this approach in the above example.\n<ul class=\"wp-block-list\">\n<li>Firstly we insert the first node in the set and move our pointer to the node next.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/J8TAEfY6eOnqy6dVNjL2_4aDHrpGNsGE0ckBibItfMt-Ps3o3fMdbAfmc2e-sAXIwkGwZA6ABS71hG1MF6s5amGnKwhwChhvBmSVO63tinguBzm-SALgl4bXnT2OGcVYF_SyR9jIxJtEi4bWRUVtvTA\" alt=\"2nd Node\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Now we will insert the 2nd node in our set and move our pointer to the next node.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/IwPod_VPN6KA9li3iguVpvZUMK3fjGATcDFFGuSr3YRcsMrXW8j3UCChitMDuXmEoobG_dyDyaAsQkdom_TxX8OCL-YScKAhdTquF6B53wT6h5AcZ2GiNsqpiaHX7f2heubRUGnbltZXJohHsCljesQ\" alt=\"3rd Node\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Now we will insert the 3rd node in our set and move our pointer to the next node.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/X2Dp2AFfE2M55EdzhsiJCUeWuuJa3x1ckMkRHUXV5sPU3HtoXp7saA-Mv56GQheMq_2L5vpJ5ic1QcDzMOztEbRe40_YiOJFJF4ol9zdDyvgcRw2HNQHoC_GdNOxJImiU-ggFXtwDzFmCGUiAlSVu6s\" alt=\"4th Node\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Now we will insert the 4th node in our set and move our pointer to the next node.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/ElBcdhyMpgULV-54uHsGJIWijR27mMXMw_3YQCSAYrzPBe7x-LX4Pnd_b1fJSIaNCE3y4XvhY1KPac1JiP_7_YCgLJ8RmuHGSnS3sbf66tBLq4mFhV6erDLq7cwMihe8wfCFWNhJBV7LLjaujx5UgtU\" alt=\"5th Node\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Now we will insert the 5th node in our set and move our pointer to the next node.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/myNMApIqMhvLXteaCeycs5RR4Emmhw2p1CVXPhUnnXyUtEEqTJndDtWnlry9uOP4-DhzMGY59mUj4m1IKfiwRJfURupE1RjPdh6ExAK-3dSIVCr_KVSxMoIlWhNwUhQl8iRRfB1gGKnGCx9DBXUogxU\" alt=\"Node is already present: Cycle Detected\" style=\"aspect-ratio:3.9263803680981595;width:1170px;height:auto\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Here we have arrived at the cycle point when we will try to insert this in our set then we will see this node is already present. And return true that there is a cycle.<\/li>\n<\/ul>\n\n\n\n<p>The time complexity of this approach is O(N) as we are iterating through the list only once and N is the size of the linked list. The space complexity of this approach is O(N) as we are using a set and storing N nodes in it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Floyd&#8217;s Tortoise &amp; Hare Algorithm to Detect Linked List Cycle<\/strong><\/h2>\n\n\n\n<p><strong>Using Floyd&#8217;s Tortoise &amp; Hare Algorithm, the concept of the slow and fast pointer is used to detect cycles in a linked list.<\/strong> It is based on the learning that whenever we move a pointer with twice the speed of another pointer if there exists any cycle, both will meet somewhere in the cycle. Since the distance will keep on decreasing between the two after every cycle is completed.<\/p>\n\n\n\n<p>Also known as the cycle detection algorithm Floyd&#8217;s Tortoise &amp; Hare Algorithm was developed by Robert W. Floyd. The basic idea behind it is to have two pointers, one moving at a slower pace (tortoise) and the other at a faster pace (hare). If there is a cycle in the sequence, the faster pointer will eventually catch up to the slower one, indicating the presence of a cycle.<\/p>\n\n\n\n<p>Below are the steps to be followed to detect a cycle or loop in a linked list using Floyd&#8217;s Tortoise and Hare algorithm:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Firstly we will Initialise two pointers, slow and fast, at the beginning of the linked list.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/guyC4U_ja4Aye4ZsIQyq_43bMQyR8hskSExnr5ZWakGo7r_vFN9LBT6tZ6ZdOm8eGximUyQvqjMg_QcW0SwMfiURdrdPrK6L5IwERM5tXM8ae9CzppZtCqEMY9tPOPgIsruaKFJIT63B_8lDBgkFeeM\" alt=\"Initialise two pointers, slow and fast\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Now Move the slow pointer one step at a time and the fast pointer two steps at a time.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/S1tP2bX0LicWKAX79ac-o8NwgszREvXP6dQEEkd9kCS47CpdxPpFirTIZ2UQ09kFjuJKRwVhLKruzrLR8kKM_nbww_4EHbThsZtcdzy9rkUbWuWSukfdbmjdidoVjNJxpu1IXUKEROAj45jEAFW1LBM\" alt=\"Move the slow pointer one step\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>If there is no cycle, the fast pointer will reach the end of the list (null reference). Else If there is a cycle, the fast pointer will eventually meet the slow pointer within the loop.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/vCxE_dAYXVdendtdWxaOngwvgbYh4xV71-oZX6kgPtQjdhrhyFEXRFYMFO3lRuQO4ptM03PKxYLj7fEO4huS8Y3xWOkg2R9-BDnKzMj9cBXnIav_MIwvupc_RCJHQFq9w6RxtkkeFGJ8sqF_tNhThbg\" alt=\"Move the fast pointer two step\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>After one more pass, both the pointers met at a point.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/lQpMPks3cPz7CfnVXr_qnW74Hxb0f-TMTa5M6hmzeBALl5zrCIrBMqbg52Ll_QzJyrxTq1Fqy97wwfUI7HyROJLf4WCk4k47ZV9U_sLNRJMcvf1aOzm2m_GTeapWjkV65pYN4mlAUnT7pahCDyzle2Q\" alt=\"Both the pointers met\"\/><\/figure>\n<\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Below is the complete C++ program for Linked List Cycle Detection:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\n\/\/ Definition for singly-linked list.\nstruct ListNode {\n    int val;\n    ListNode* next;\n    ListNode(int x) : val(x), next(nullptr) {}\n};\n\nbool hasCycle(ListNode* head) {\n    \/\/ Initialize fast and slow pointers\n    ListNode* slow = head;\n    ListNode* fast = head;\n\n    \/\/ Traverse the linked list\n    while (fast != nullptr &amp;&amp; fast-&gt;next != nullptr) {\n        \/\/ Move slow pointer one step\n        slow = slow-&gt;next;\n\n        \/\/ Move fast pointer two steps\n        fast = fast-&gt;next-&gt;next;\n\n        \/\/ Check if pointers meet, indicating a cycle\n        if (slow == fast) {\n            return true;\n        }\n    }\n\n    \/\/ If the end of the list is reached and no cycle is detected\n    return false;\n}\n\nint main() {\n    \/\/ Create a linked list: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 3 (cycle)\n    ListNode* head = new ListNode(1);\n    head-&gt;next = new ListNode(2);\n    head-&gt;next-&gt;next = new ListNode(3);\n    head-&gt;next-&gt;next-&gt;next = new ListNode(4);\n    head-&gt;next-&gt;next-&gt;next-&gt;next = new ListNode(5);\n    head-&gt;next-&gt;next-&gt;next-&gt;next-&gt;next = head-&gt;next-&gt;next;  \/\/ Creating a cycle\n\n    \/\/ Check if the linked list has a cycle\n    if (hasCycle(head)) {\n        cout &lt;&lt; &quot;The linked list has a cycle.&quot; &lt;&lt; endl;\n    } else {\n        cout &lt;&lt; &quot;The linked list does not have a cycle.&quot; &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>You can detect loop or cycle in linked list using Java as well:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">public class LinkedListCycle {\n\n    \/\/ Definition for singly-linked list.\n    static class ListNode {\n        int val;\n        ListNode next;\n        ListNode(int x) {\n            val = x;\n            next = null;\n        }\n    }\n\n    public static boolean hasCycle(ListNode head) {\n        \/\/ Initialize fast and slow pointers\n        ListNode slow = head;\n        ListNode fast = head;\n\n        \/\/ Traverse the linked list\n        while (fast != null &amp;&amp; fast.next != null) {\n            \/\/ Move slow pointer one step\n            slow = slow.next;\n\n            \/\/ Move fast pointer two steps\n            fast = fast.next.next;\n\n            \/\/ Check if pointers meet, indicating a cycle\n            if (slow == fast) {\n                return true;\n            }\n        }\n\n        \/\/ If the end of the list is reached and no cycle is detected\n        return false;\n    }\n\n    public static void main(String[] args) {\n        \/\/ Create a linked list: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 3 (cycle)\n        ListNode head = new ListNode(1);\n        head.next = new ListNode(2);\n        head.next.next = new ListNode(3);\n        head.next.next.next = new ListNode(4);\n        head.next.next.next.next = new ListNode(5);\n        head.next.next.next.next.next = head.next.next;  \/\/ Creating a cycle\n\n        \/\/ Check if the linked list has a cycle\n        if (hasCycle(head)) {\n            System.out.println(&quot;The linked list has a cycle.&quot;);\n        } else {\n            System.out.println(&quot;The linked list does not have a cycle.&quot;);\n        }\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Here is the implementation in Python also:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">class ListNode:\n    def __init__(self, x):\n        self.val = x\n        self.next = None\n\ndef hasCycle(head):\n    # Initialize fast and slow pointers\n    slow = head\n    fast = head\n\n    # Traverse the linked list\n    while fast is not None and fast.next is not None:\n        # Move slow pointer one step\n        slow = slow.next\n\n        # Move fast pointer two steps\n        fast = fast.next.next\n\n        # Check if pointers meet, indicating a cycle\n        if slow == fast:\n            return True\n\n    # If the end of the list is reached and no cycle is detected\n    return False\n\n# Create a linked list: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 3 (cycle)\nhead = ListNode(1)\nhead.next = ListNode(2)\nhead.next.next = ListNode(3)\nhead.next.next.next = ListNode(4)\nhead.next.next.next.next = ListNode(5)\nhead.next.next.next.next.next = head.next.next  # Creating a cycle\n\n# Check if the linked list has a cycle\nif hasCycle(head):\n    print(&quot;The linked list has a cycle.&quot;)\nelse:\n    print(&quot;The linked list does not have a cycle.&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>The linked list has a cycle.<\/code><\/pre>\n\n\n\n<p>The time complexity of this approach is<strong> O(N) <\/strong>where N is the size of the linked list. In the worst case, all the nodes of the list are visited. The space complexity is<strong> O(1) <\/strong>because we are not using any extra space.<\/p>\n\n\n\n<p>Below is a small comparative analysis of both the methods:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Approaches<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Time complexity<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Space complexity<\/strong><\/td><td><strong>Details<\/strong><\/td><\/tr><tr><td>Hashing Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(N)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(N)<\/td><td>Here space complexity is O(N) because we are using a set data structure to detect cycle<\/td><\/tr><tr><td>Optimized approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(N)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td>Here no extra space is required in this approach<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>You might also want to learn how to <a href=\"https:\/\/favtutor.com\/blogs\/detect-cycle-in-undirected-graph\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/blogs\/detect-cycle-in-undirected-graph\">detect a cycle in an undirected graph<\/a> as well.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In conclusion, we solve the <a href=\"https:\/\/leetcode.com\/problems\/linked-list-cycle\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/leetcode.com\/problems\/linked-list-cycle\/\" rel=\"noreferrer noopener nofollow\">leetcode problem<\/a> titled &#8216;Linked List Cycle&#8217; and how to detect the cycle in a linked list using two different approaches, i.e. using hashing and Floyd\u2019s Tortoise and Hare Algorithm. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand the Linked List Cycle leetcode problem to detect a cycle or a loop in a linked list using Floyd&#8217;s Tortoise and Hare algorithm.<\/p>\n","protected":false},"author":12,"featured_media":1062,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1060","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1060","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1060"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1060\/revisions"}],"predecessor-version":[{"id":1092,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1060\/revisions\/1092"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1062"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1060"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1060"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1060"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}