Linked List¶
Floyd’s Tortoise and Hare¶
Description¶
Floyd’s cycle-finding algorithm is a pointer algorithm that uses only two pointers, which move through the sequence at different speeds. It is also called the tortoise and the hare algorithm
Checking the existence of the cycle in the linked-list. We can also find the node with which linked-list is linked
Important
Linear TIme
Constant Space
See also
Reference : wiki
Python¶
Check For Cycle¶
def check_cycle(self, head):
"""
Return True is cycle is present else False
:param head:
:return:
"""
# Two pointers
tortoise, hare = head, head
# Base Case
while hare and hare.next:
tortoise = tortoise.next
hare = hare.next.next
# Condition for cycle
if tortoise == hare:
return True
# Condition when there is no cycle
return False
Get the Node where cycle exists¶
def cycle_node(self, head):
"""
Finding the node where cycle exists
:param head:
:return:
"""
# Two pointers
tortoise, hare = head, head
while True:
# Condition when pointer reaches to end
if not hare or not hare.next:
return None
tortoise = tortoise.next
hare = hare.next.next
if tortoise == hare:
break
# Iterating over the ll to find
tortoise = head
while tortoise != hare:
tortoise = tortoise.next
hare = hare.next
# Returning node where cycle was found
return tortoise
Implementation¶
Sl No |
Level |
Questions |
Solutions |
Tags |
---|---|---|---|---|
141 |
Easy |
Two Pointers |
||
142 |
Medium |
Hash-Table, Two Pointers |