Linked List Cycle
Problem Summary
- Given a linked list, return true if it has cycle else false
Key Observations
- Solve it in
space complexity
Why This Works
(Explain the core reason the solution is correct.)
Main Concepts Used
(Mark the CS concepts or algorithms used.)
Time & Space Complexity
- Time:
→ Reason: Iterating through the linked list once - Space:
→ Reason: Not storing a copy
Code
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow, fast = head, head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow == fast:
return True
return False
Common Mistakes / Things I Got Stuck On
- Need to make sure slow and fast are not the same initially or move once before doing the
if slow == fastcheck