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.