diff --git a/linked_lists/find_loop_start/find_loop_start_solution.ipynb b/linked_lists/find_loop_start/find_loop_start_solution.ipynb index b687bb7..102d927 100644 --- a/linked_lists/find_loop_start/find_loop_start_solution.ipynb +++ b/linked_lists/find_loop_start/find_loop_start_solution.ipynb @@ -60,12 +60,12 @@ "source": [ "## Algorithm\n", "\n", - "* Use two pointers i, j, initialized to the head\n", - "* Increment i and j until they meet\n", - " * j is incremented twice as fast as i\n", - " * If j's next is None, we do not have a circular list\n", - "* When i and j meet, move j to the head\n", - "* Increment i and j one node at a time until they meet\n", + "* Use two references `slow`, `fast`, initialized to the `head`\n", + "* Increment `slow` and `fast` until they meet\n", + " * `fast` is incremented twice as fast as `slow`\n", + " * If `fast.next` is `None`, we do not have a circular list\n", + "* When `slow` and `fast` meet, move `slow` to the `head`\n", + "* Increment `slow` and `fast` one node at a time until they meet\n", "* Where they meet is the start of the loop\n", "\n", "Complexity:\n", @@ -103,29 +103,23 @@ "\n", " def find_loop_start(self):\n", " if self.head is None or self.head.next is None:\n", - " return\n", - " i = self.head\n", - " j = self.head\n", - " i = i.next\n", - " j = j.next.next\n", - "\n", - " # Increment i and j until they meet\n", - " # j is incremented twice as fast as i\n", - " while j != i:\n", - " i = i.next\n", - " if j is None or j.next is None:\n", - " return\n", - " j = j.next.next\n", - "\n", - " # When i and j meet, move j to the head\n", - " j = self.head\n", - "\n", - " # Increment i and j one node at a time until\n", - " # they meet, which is the start of the loop\n", - " while j != i:\n", - " i = i.next\n", - " j = j.next\n", - " return i.data" + " return None\n", + " slow = self.head\n", + " fast = self.head\n", + " while fast.next is not None:\n", + " slow = slow.next\n", + " fast = fast.next.next\n", + " if fast is None:\n", + " return None\n", + " if slow.data == fast.data:\n", + " break\n", + " slow = self.head\n", + " while slow.data != fast.data:\n", + " slow = slow.next\n", + " fast = fast.next\n", + " if fast is None:\n", + " return None\n", + " return slow.data" ] }, { @@ -230,21 +224,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.10" + "pygments_lexer": "ipython3", + "version": "3.4.3" } }, "nbformat": 4,