Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

linked-list-cycle.py

linked-lists/linked-list-cycle.py · Python · 655 B · 2026-02-17 21:03

Back to folder
# Use a set. Or 2 pointers (fast and slow).
# linked-lists


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# O(n) time | O(n) space
def hasCycle(head: ListNode | None) -> bool:
    seen = set()
    curr = head
    while curr:
        if curr in seen:
            return True
        seen.add(curr)
        curr = curr.next
    return False

# O(n) time | O(1) space
def hasCycle1(head: ListNode | None) -> bool:
    slow = head
    fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False