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.