Linked List Cycle - Solution
Solutions and explanations

Video Explanation

# 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:
        visited = set()
        cur = head
        while cur:
            if cur in visited:
                return True
            visited.add(cur)
            cur = cur.next
        return False

Complexity Analysis

Here, n is the number of elements in the linked list.

  • Time Complexity: O(n)
  • Space Complexity: O(n)

# 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:
        # Floyd's Tortoise and Hare Algorithm (Slow and Fast Pointers)
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

Complexity Analysis

Here, n is the number of elements in the linked list.

  • Time Complexity: O(n)
  • Space Complexity: O(1)