2 minute read

141. Linked List Cycle

Difficulty: Easy

Related Topics: Hash Table, Linked List, Two Pointers

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.

First Attempt:

Code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        node = []
        while head != None and head.next != None:
            if head.next in node:
                return True
            else:
                node.append(head.next)
            head = head.next
        return False

Feedbacks:

I created a node to store head.next. As I traverse through the linked list, If head.next is in node list, It means there exist a cycle inside the linked list, So I return True. Else, if while loop ends, it means head.next is none meaning there’s no cycle and it is singly linked list, I can return False. But this code is too slow. I need to optimize this. Since related topics include two pointers, may be I can use that.

Second Attempt:

Code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head:
            return False
        slow = head
        fast = head.next
        while slow != fast:
            if not fast or not fast.next:
                return False
            slow = slow.next
            fast = fast.next.next
        return True

Feedbacks:

I make two pointers slow and fast. If head is None, return False (linked list does not exist). Slow increment by one, fast increment by two. If slow is not equal to fast and if they are not None, I increment two pointers again. Else, I return False, because it means slow or fast is None. Slow and Fast is important to know I think. One pointer increases by one, and another pointer increases by two.