Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 142 · Fast & Slow Pointers

Linked List Cycle II

LeetCode 142 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Meet, reset one to head, step together → cycle start.

మధ్యస్థంHash TableLinked ListTwo PointersFloyd's Cycle Finding Algorithm
LeetCode లో తెరవండి ↗

నేను Linked List Cycle II (LeetCode 142) ను ఇలా పరిష్కరించాను — Fast & Slow Pointers ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

After slow and fast meet inside the loop, the distance from the head to the loop entrance equals the distance from the meeting point to the entrance (going around). Restart one pointer from the head and step both by one: they meet exactly at the entrance.

Approach

  1. 1

    Phase 1: Floyd until slow == fast (or fast reaches the end → no cycle).

  2. 2

    Phase 2: fast = head.

  3. 3

    Advance both by one until they meet; return that node.

నేను ఎలా పరిష్కరించాను

Floyd two-phasePythonO(n) time · O(1) space
class Solution:
    def detectCycle(self, head):
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                break
        if fast is None or fast.next is None:
            return None
        fast = head
        while slow != fast:
            slow = slow.next
            fast = fast.next
        return slow
స్టెప్-త్రూ లోడ్ అవుతోంది…

Linked List Cycle II — తరచూ అడిగే ప్రశ్నలు

Linked List Cycle II వెనుక ఉన్న intuition ఏమిటి?

After slow and fast meet inside the loop, the distance from the head to the loop entrance equals the distance from the meeting point to the entrance (going around). Restart one pointer from the head and step both by one: they meet exactly at the entrance.

Linked List Cycle II (LeetCode 142) ను ఎలా పరిష్కరించాలి?

1. Phase 1: Floyd until slow == fast (or fast reaches the end → no cycle). 2. Phase 2: fast = head. 3. Advance both by one until they meet; return that node.

Linked List Cycle II యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(1). (Accepted approach: Floyd two-phase.)

Linked List Cycle II లో సాధారణ పొరపాట్లు ఏమిటి?

Return null when phase 1 ends without meeting.