Skip to content

Latest commit

 

History

History
124 lines (95 loc) · 3.21 KB

_142. Linked List Cycle II.md

File metadata and controls

124 lines (95 loc) · 3.21 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 26, 2024

Last updated : June 26, 2024


Related Topics : Hash Table, Linked List, Two Pointers

Acceptance Rate : 52.88 %


Solutions

Python

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

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head :
            return None
            
        currFast = head
        currSlow = head

        loop: bool = False
        while currFast.next and currFast.next.next :
            currFast = currFast.next.next
            currSlow = currSlow.next

            if currFast == currSlow :
                loop = True
                break

        if not loop :
            return None

        loopSize = 1
        currFast = currFast.next
        while currFast != currSlow :
            loopSize += 1
            currFast = currFast.next
        
        currRef = head
        while True :
            for i in range(loopSize) :
                currFast = currFast.next
                if currFast == currRef :
                    return currRef
            currRef = currRef.next
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head :
            return None
        
        past = set()

        while head :
            if head in past :
                return head
            
            past.add(head)
            head = head.next
        return None
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head :
            return None
            
        currFast = head
        currSlow = head

        while currFast.next and currFast.next.next :
            currFast = currFast.next.next
            currSlow = currSlow.next

            if currFast == currSlow : # Loop found
                currSlow = head
                while currSlow != currFast :
                    currSlow = currSlow.next
                    currFast = currFast.next

                return currSlow
        return None