141. Linked List Cycle I
Given head
, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next
pointer. Internally, pos
is used to denote the index of the node that tail's next
pointer is connected to. Note that pos
is not passed as a parameter.
Return true
if there is a cycle in the linked list. Otherwise, return false
.
Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints:
- The number of the nodes in the list is in the range
[0, 104]
. -105 <= Node.val <= 105
pos
is-1
or a valid index in the linked-list.
Approach 1:
Using hash set
As we traverse the linked list , we basically store the address of each of the visited nodes to a hash set and then check if next pointer of current node points to any of the previously visited node, if yes then returns that node to which this current node points, else returns none
def detectCycle(self, head):
temp=head
hash_set=set()
index=0
while(temp!=None):
if(temp.next in hash_set):
return True
else:
hash_set.add(temp)
temp=temp.next
return False
Time :O(n)
Space :O(n)
Approach 2:
This is a solution which is better in terms of space and time , since we are already provided with the constraint that at most 1⁰⁴ nodes can be in the list, and in case of presence of a cycle , if we traverse the linked list until we find a null value , the iteration would go far beyond 1⁰⁴ , therefore this is a worthy condition to attribute to the presence of a cycle.
def hasCycle(self, head):
cnt=0
temp=head
while(temp!=None):
cnt+=1
if cnt>10**4:
return True
temp=temp.next
return False
Time :O(n)
Space:O(1)
Approach 3:
Floyd’s algo