Skip to content

Latest commit

 

History

History

141-LinkedListCycle

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Linked List Cycle

Problem can be found in here!

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

Solution: Fast Slow Pointers

def hasCycle(head: Optional[ListNode]) -> bool:
    fast_pointer = slow_pointer = head

    while fast_pointer and fast_pointer.next:
        fast_pointer, slow_pointer = fast_pointer.next.next, slow_pointer.next
        if fast_pointer == slow_pointer:
            return True

    return False

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