Linked List Cycle
LeetCode 141 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Floyd: fast meets slow ⇔ cycle.
मैंने 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
slow and fast start at head.
- 2
Advance slow by 1 and fast by 2.
- 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 FalseLinked 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.