class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow is fast:
return True
return False
# Time Complexity: O(n)
# Space Complexity: O(1)
The “Linked List Cycle” problem asks us to determine whether a given singly linked list contains a cycle. A cycle occurs when a node's next pointer points to a previously visited node, causing the list to loop indefinitely.
Example:
truenullfalseDetecting cycles in a linked list is a foundational algorithm in computer science and has practical applications in memory management, graph traversal, and detecting infinite loops. This problem is also a great introduction to the two-pointer (tortoise and hare) technique.
The most efficient method to detect a cycle in a linked list is to use two pointers:
If a cycle exists, the fast pointer will eventually “lap” the slow pointer — they will meet at some point. If there is no cycle, the fast pointer will reach the end of the list.
slow and fast pointers at the head of the list.fast and fast.next are not null:
slow one step forward (slow = slow.next).fast two steps forward (fast = fast.next.next).slow === fast, a cycle exists — return true.false.
Input: 3 → 2 → 0 → -4, with -4 pointing back to 2
Execution:
true
Time Complexity: O(n), where n is the number of nodes. In the worst case, fast pointer visits each node at most twice.
Space Complexity: O(1), as no additional data structures are used.
falsefalsetrueThe “Linked List Cycle” problem is a classic use of the two-pointer technique. It shows how clever pointer manipulation can solve problems efficiently without the need for additional memory. Mastering this approach will prepare you for more advanced problems involving cycles and fast-slow pointer techniques in graphs and linked lists.