141. Linked List Cycle¶
Summary¶
| Solution Approach | Explanation (1-minute) | Time Complexity | Space Complexity |
|---|---|---|---|
| Hash Set | Store visited nodes in a set. If we encounter a node already in the set, there's a cycle. | \(O(n)\) | \(O(n)\) |
| Two Pointers (Floyd's Cycle Detection) | Use slow and fast pointers. Slow moves 1 step, fast moves 2 steps. If they meet, there's a cycle. | \(O(n)\) | \(O(1)\) |
Implementation¶
# 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:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False