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.
true if there is a cycle in the linked list. Otherwise, return
Input: head = [3,2,0,-4], pos = 1
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Input: head = [1,2], pos = 0
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Input: head = , pos = -1
Explanation: There is no cycle in the linked list.
- The number of the nodes in the list is in the range
-105 <= Node.val <= 105
-1or a valid index in the linked-list.
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):
if(temp.next in hash_set):
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):