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

मैंने 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.