Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 141 · Fast & Slow Pointers

Linked List Cycle

LeetCode 141 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Floyd: fast meets slow ⇔ cycle.

सोपाHash TableLinked ListTwo PointersFloyd's Cycle Finding Algorithm

मी Linked List Cycle (LeetCode 141) असा सोडवला — Fast & Slow Pointers पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Send a slow pointer one step and a fast pointer two steps. If there is a loop, the fast one eventually laps the slow one and they meet; if not, the fast pointer reaches the end.

Approach

  1. 1

    slow and fast start at head.

  2. 2

    Advance slow by 1 and fast by 2.

  3. 3

    Equal → cycle; fast hits None → no cycle.

मी कसा सोडवला

Floyd's cycle detectionPythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = head
        fast = head
        while fast and fast.next!=None:
            slow = slow.next
            fast = fast.next.next
            if slow==fast:
                return True
        return False
स्टेप-थ्रू लोड होत आहे…

Linked List Cycle — वारंवार विचारले जाणारे प्रश्न

Linked List Cycle मागील intuition काय आहे?

Send a slow pointer one step and a fast pointer two steps. If there is a loop, the fast one eventually laps the slow one and they meet; if not, the fast pointer reaches the end.

Linked List Cycle (LeetCode 141) कसा सोडवावा?

1. slow and fast start at head. 2. Advance slow by 1 and fast by 2. 3. Equal → cycle; fast hits None → no cycle.

Linked List Cycle ची time आणि space complexity किती आहे?

Time: O(n). Space: O(1). (Accepted approach: Floyd's cycle detection.)

Linked List Cycle मध्ये सामान्य चुका कोणत्या?

Compare nodes (identity), not values.