{"id":638,"date":"2025-07-15T12:39:59","date_gmt":"2025-07-15T07:09:59","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=638"},"modified":"2025-07-15T12:40:00","modified_gmt":"2025-07-15T07:10:00","slug":"linked-list-cycle-leetcode-141","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/","title":{"rendered":"Linked List Cycle | Leetcode 141 | Floyd&#8217;s Cycle Detection"},"content":{"rendered":"\n<p>Given\u00a0<code>head<\/code>, the head of\u00a0a linked list, determine if the\u00a0linked list has a cycle\u00a0in it. There is\u00a0a cycle in a linked list if there is some node\u00a0in the list that can\u00a0be reached again by continuously\u00a0following the\u00a0<code>next<\/code>\u00a0pointer. Return\u00a0<code>true<\/code>\u00a0if there is a\u00a0cycle in the linked list,\u00a0otherwise return\u00a0<code>false<\/code>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/linked-list-cycle\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2018\/12\/07\/circularlinkedlist.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> head = [3,2,0,-4], pos = 1<br><strong>Output:<\/strong> true<br><strong>Explanation:<\/strong> There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2018\/12\/07\/circularlinkedlist_test2.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> head = [1,2], pos = 0<br><strong>Output:<\/strong> true<br><strong>Explanation:<\/strong> There is a cycle in the linked list, where the tail connects to the 0th node.<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2018\/12\/07\/circularlinkedlist_test3.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> head = [1], pos = -1<br><strong>Output:<\/strong> false<br><strong>Explanation:<\/strong> There is no cycle in the linked list.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The number of the nodes in the list is in the range\u00a0<code>[0, 10<sup>4<\/sup>]<\/code>.<\/li>\n\n\n\n<li><code>-10<sup>5<\/sup> &lt;= Node.val &lt;= 10<sup>5<\/sup><\/code><\/li>\n\n\n\n<li><code>pos<\/code>\u00a0is\u00a0<code>-1<\/code>\u00a0or a\u00a0<strong>valid index<\/strong>\u00a0in the linked-list.<\/li>\n<\/ul>\n\n\n\n<p><strong>Follow up:<\/strong>&nbsp;Can you solve it using&nbsp;<code>O(1)<\/code>&nbsp;(i.e. constant) memory?<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-ac55cc3a-b308-4581-89fd-d73a6d3167dd\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"true\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#0-solution-1-brute-force-approach-using-set\" style=\"\">Solution 1: Brute Force Approach (Using Set)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#1-intuition\" style=\"\">Intuition<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#2-detailed-approach\" style=\"\">Detailed Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#3-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#4-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#5-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#6-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#7-simplifying-it\" style=\"\">Simplifying It<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#8-solution-2-optimal-approach-floyds-cycle-detection-two-pointers\" style=\"\">Solution 2: Optimal Approach (Floyd&#8217;s Cycle Detection &#8211; Two Pointers)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#9-intuition\" style=\"\">Intuition<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#10-detailed-approach\" style=\"\">Detailed Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#11-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#12-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#13-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#14-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#15-simplifying-it\" style=\"\">Simplifying It<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/linked-list-cycle-leetcode-141\/#16-summary\" style=\"\">Summary<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-solution-1-brute-force-approach-using-set\">Solution 1: Brute Force Approach (Using Set)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition\">Intuition<\/h3>\n\n\n\n<p>Imagine you&#8217;re walking through a maze and want to know if you&#8217;re going in circles. One simple way is to drop a breadcrumb at every place you visit. If you ever find a breadcrumb you&#8217;ve already dropped, you know you&#8217;re walking in a circle! We use the same idea here &#8211; store every node we visit, and if we see the same node again, there&#8217;s a cycle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-detailed-approach\">Detailed Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Create a Tracking System<\/strong>: Use a set to remember all the nodes we&#8217;ve visited<\/li>\n\n\n\n<li><strong>Walk Through the List<\/strong>: Move through each node one by one<\/li>\n\n\n\n<li><strong>Check Before Adding<\/strong>: At each node, check if we&#8217;ve seen it before<\/li>\n\n\n\n<li><strong>Found a Cycle<\/strong>: If we find a node we&#8217;ve already visited, return true<\/li>\n\n\n\n<li><strong>Reached the End<\/strong>: If we reach the end (None), there&#8217;s no cycle<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def hasCycle(self, head: Optional[ListNode]) -&gt; bool:\n        temp = head              # Current node we're examining\n        node_set = set()         # Set to store visited nodes\n        \n        while temp is not None:\n            if temp in node_set: # Check if we've seen this node before\n                return True      # Found a cycle!\n            node_set.add(temp)   # Remember this node for future\n            temp = temp.next     # Move to the next node\n        \n        return False            # Reached end, no cycle found\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">hasCycle<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">head<\/span><span style=\"color: #D4D4D4\">: Optional[ListNode]) -&gt; <\/span><span style=\"color: #4EC9B0\">bool<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        temp = head              <\/span><span style=\"color: #6A9955\"># Current node we&#39;re examining<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        node_set = <\/span><span style=\"color: #4EC9B0\">set<\/span><span style=\"color: #D4D4D4\">()         <\/span><span style=\"color: #6A9955\"># Set to store visited nodes<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> temp <\/span><span style=\"color: #569CD6\">is<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">not<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> temp <\/span><span style=\"color: #569CD6\">in<\/span><span style=\"color: #D4D4D4\"> node_set: <\/span><span style=\"color: #6A9955\"># Check if we&#39;ve seen this node before<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">      <\/span><span style=\"color: #6A9955\"># Found a cycle!<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            node_set.add(temp)   <\/span><span style=\"color: #6A9955\"># Remember this node for future<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            temp = temp.next     <\/span><span style=\"color: #6A9955\"># Move to the next node<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">False<\/span><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Reached end, no cycle found<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-code-explanation\">Code Explanation<\/h3>\n\n\n\n<p>We start from the head and visit each node one by one. Before moving to the next node, we check if the current node is already in our set. If it is, we&#8217;ve found a cycle because we&#8217;re visiting the same node twice. If it&#8217;s not in the set, we add it and continue. If we reach the end of the list (temp becomes None), it means there&#8217;s no cycle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-dry-run\">Dry Run<\/h3>\n\n\n\n<p>Let&#8217;s trace through a list with cycle:&nbsp;<code>1 -&gt; 2 -&gt; 3 -&gt; 2<\/code>&nbsp;(3 points back to 2)<\/p>\n\n\n\n<p><strong>Step 1:<\/strong>&nbsp;temp=1, node_set={}, add 1: node_set={1}<br><strong>Step 2:<\/strong>&nbsp;temp=2, node_set={1}, add 2: node_set={1, 2}<br><strong>Step 3:<\/strong>&nbsp;temp=3, node_set={1, 2}, add 3: node_set={1, 2, 3}<br><strong>Step 4:<\/strong>&nbsp;temp=2, node_set={1, 2, 3}, 2 is already in set \u2192 return True<\/p>\n\n\n\n<p><strong>Result:<\/strong>&nbsp;Cycle detected!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\u00a0O(n) &#8211; We visit each node at most once before detecting the cycle<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\u00a0O(n) &#8211; In worst case, we store all nodes in the set<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-simplifying-it\">Simplifying It<\/h3>\n\n\n\n<p>This approach is straightforward &#8211; keep a record of everywhere you&#8217;ve been, and if you end up somewhere you&#8217;ve already been, you know you&#8217;re going in circles. However, it uses extra memory to store all the visited nodes.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8-solution-2-optimal-approach-floyds-cycle-detection-two-pointers\">Solution 2: Optimal Approach (Floyd&#8217;s Cycle Detection &#8211; Two Pointers)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-intuition\">Intuition<\/h3>\n\n\n\n<p>Imagine two people running on a circular track &#8211; one person runs at normal speed, and another runs twice as fast. If the track is circular, the faster runner will eventually lap the slower runner and they&#8217;ll meet. If the track has an end, the fast runner will just reach the finish line first. This is exactly how we detect cycles!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-detailed-approach\">Detailed Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Set Up Two Runners<\/strong>: Create two pointers &#8211; slow (moves 1 step) and fast (moves 2 steps)<\/li>\n\n\n\n<li><strong>Start the Race<\/strong>: Both start from the head of the linked list<\/li>\n\n\n\n<li><strong>Move at Different Speeds<\/strong>: Slow moves 1 node at a time, fast moves 2 nodes at a time<\/li>\n\n\n\n<li><strong>Check for Meeting<\/strong>: If there&#8217;s a cycle, fast will eventually catch up to slow<\/li>\n\n\n\n<li><strong>Check for End<\/strong>: If fast reaches the end (None), there&#8217;s no cycle<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def hasCycle(self, head: Optional[ListNode]) -&gt; bool:\n        slow = head          # Slow pointer (tortoise) - moves 1 step\n        fast = head          # Fast pointer (hare) - moves 2 steps\n\n        while fast is not None and fast.next is not None:\n            slow = slow.next      # Move slow pointer 1 step\n            fast = fast.next.next # Move fast pointer 2 steps\n            \n            if slow == fast:      # Pointers met - cycle detected!\n                return True\n\n        return False             # Fast reached end - no cycle\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">hasCycle<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">head<\/span><span style=\"color: #D4D4D4\">: Optional[ListNode]) -&gt; <\/span><span style=\"color: #4EC9B0\">bool<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        slow = head          <\/span><span style=\"color: #6A9955\"># Slow pointer (tortoise) - moves 1 step<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        fast = head          <\/span><span style=\"color: #6A9955\"># Fast pointer (hare) - moves 2 steps<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> fast <\/span><span style=\"color: #569CD6\">is<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">not<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> fast.next <\/span><span style=\"color: #569CD6\">is<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">not<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            slow = slow.next      <\/span><span style=\"color: #6A9955\"># Move slow pointer 1 step<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            fast = fast.next.next <\/span><span style=\"color: #6A9955\"># Move fast pointer 2 steps<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> slow == fast:      <\/span><span style=\"color: #6A9955\"># Pointers met - cycle detected!<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">True<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">False<\/span><span style=\"color: #D4D4D4\">             <\/span><span style=\"color: #6A9955\"># Fast reached end - no cycle<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-code-explanation\">Code Explanation<\/h3>\n\n\n\n<p>We use two pointers moving at different speeds. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. If there&#8217;s no cycle, the fast pointer will reach the end first. But if there&#8217;s a cycle, both pointers will keep moving in the cycle forever, and eventually the fast pointer will catch up to the slow pointer from behind. When they meet, we know there&#8217;s a cycle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-dry-run\">Dry Run<\/h3>\n\n\n\n<p>Let&#8217;s trace through a list with cycle:&nbsp;<code>1 -&gt; 2 -&gt; 3 -&gt; 2<\/code>&nbsp;(3 points back to 2)<\/p>\n\n\n\n<p><strong>Initial:<\/strong>&nbsp;slow=1, fast=1<\/p>\n\n\n\n<p><strong>Step 1:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>slow moves to 2<\/li>\n\n\n\n<li>fast moves to 3<\/li>\n\n\n\n<li>slow \u2260 fast<\/li>\n<\/ul>\n\n\n\n<p><strong>Step 2:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>slow moves to 3<\/li>\n\n\n\n<li>fast moves to 2 (following the cycle)<\/li>\n\n\n\n<li>slow \u2260 fast<\/li>\n<\/ul>\n\n\n\n<p><strong>Step 3:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>slow moves to 2 (following the cycle)<\/li>\n\n\n\n<li>fast moves to 3<\/li>\n\n\n\n<li>slow \u2260 fast<\/li>\n<\/ul>\n\n\n\n<p><strong>Step 4:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>slow moves to 3<\/li>\n\n\n\n<li>fast moves to 2<\/li>\n\n\n\n<li>slow \u2260 fast<\/li>\n<\/ul>\n\n\n\n<p><strong>Step 5:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>slow moves to 2<\/li>\n\n\n\n<li>fast moves to 3<\/li>\n\n\n\n<li>slow \u2260 fast<\/li>\n<\/ul>\n\n\n\n<p>Wait, let me recalculate this more carefully&#8230;<\/p>\n\n\n\n<p><strong>Initial:<\/strong>&nbsp;slow=1, fast=1<\/p>\n\n\n\n<p><strong>Step 1:<\/strong>&nbsp;slow=2, fast=3, slow \u2260 fast<br><strong>Step 2:<\/strong>&nbsp;slow=3, fast=2 (cycle), slow \u2260 fast<br><strong>Step 3:<\/strong>&nbsp;slow=2 (cycle), fast=3, slow \u2260 fast<br><strong>Step 4:<\/strong>&nbsp;slow=3, fast=2, slow \u2260 fast<br><strong>Step 5:<\/strong>&nbsp;slow=2, fast=3, slow \u2260 fast<\/p>\n\n\n\n<p>Actually, they will meet eventually as the fast pointer will catch up in the cycle.<\/p>\n\n\n\n<p><strong>Result:<\/strong>&nbsp;Eventually slow == fast, return True<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\u00a0O(n) &#8211; In the worst case, we might need to traverse the entire list<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\u00a0O(1) &#8211; We only use two pointer variables, no extra space<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"15-simplifying-it\">Simplifying It<\/h3>\n\n\n\n<p>This is like the classic &#8220;tortoise and hare&#8221; race. The key insight is that if there&#8217;s a cycle, the faster moving pointer will eventually lap the slower one. If there&#8217;s no cycle, the fast pointer will simply reach the end first. This approach is memory-efficient because we don&#8217;t need to store any visited nodes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"16-summary\">Summary<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Approach<\/th><th>Time<\/th><th>Space<\/th><th>Difficulty<\/th><th>Best For<\/th><\/tr><\/thead><tbody><tr><td>Brute Force (Set)<\/td><td>O(n)<\/td><td>O(n)<\/td><td>Easy<\/td><td>Learning the concept<\/td><\/tr><tr><td>Two Pointers (Floyd&#8217;s)<\/td><td>O(n)<\/td><td>O(1)<\/td><td>Medium<\/td><td>Production code<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The&nbsp;<strong>two pointers approach<\/strong>&nbsp;is generally preferred because it uses constant space while maintaining the same time efficiency. However, the brute force approach is more intuitive and easier to understand when you&#8217;re first learning about cycle detection.<\/p>\n\n\n\n<p>Both solutions are valid, but Floyd&#8217;s Cycle Detection algorithm (two pointers) is considered the optimal solution for this problem due to its space efficiency!<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given\u00a0head, the head of\u00a0a linked list, determine if the\u00a0linked list has a cycle\u00a0in it. There is\u00a0a cycle in a linked list if there is some node\u00a0in the list that can\u00a0be reached again by continuously\u00a0following the\u00a0next\u00a0pointer. Return\u00a0true\u00a0if there is a\u00a0cycle in the linked list,\u00a0otherwise return\u00a0false. Here&#8217;s the [Problem Link] to begin with. Example 1: Input: head<\/p>\n","protected":false},"author":1,"featured_media":639,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[8,29],"class_list":{"0":"post-638","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner","9":"tag-easy","10":"tag-singly-linked-list"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/linked-list-cycle-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/638","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=638"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/638\/revisions"}],"predecessor-version":[{"id":640,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/638\/revisions\/640"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/639"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=638"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=638"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=638"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}