Linked List Cycle II
LeetCode 142 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Meet, reset one to head, step together → cycle start.
আমি 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
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.
আমি কীভাবে সমাধান করেছি
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 slowLinked 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.