Intersection of Two Linked Lists
LeetCode 160 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Switch heads at the end; equal path lengths make them meet.
আমি Intersection of Two Linked Lists (LeetCode 160) এভাবে সমাধান করেছি — Intersection প্যাটার্নের একটি সহজ প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Walk pointer A through list A then list B, and pointer B through list B then list A. Both travel the same total distance, so they line up and meet at the intersection — or both reach the end together if there isn't one.
Approach
- 1
p1 = headA, p2 = headB.
- 2
Step both; when one reaches the end, jump to the other list's head.
- 3
Stop when they're the same node (or both None).
আমি কীভাবে সমাধান করেছি
Two-pointer head switchingPythonO(m+n) time · O(1) space
class Solution:
def getIntersectionNode(self, headA, headB):
p1 = headA
p2 = headB
while p1 != p2:
p1 = headB if p1 is None else p1.next
p2 = headA if p2 is None else p2.next
return p1Intersection of Two Linked Lists — সাধারণ প্রশ্ন
Intersection of Two Linked Lists-এর পেছনে intuition কী?
Walk pointer A through list A then list B, and pointer B through list B then list A. Both travel the same total distance, so they line up and meet at the intersection — or both reach the end together if there isn't one.
Intersection of Two Linked Lists (LeetCode 160) কীভাবে সমাধান করবেন?
1. p1 = headA, p2 = headB. 2. Step both; when one reaches the end, jump to the other list's head. 3. Stop when they're the same node (or both None).
Intersection of Two Linked Lists-এর time আর space complexity কত?
Time: O(m + n)। Space: O(1)। (Accepted approach: Two-pointer head switching।)
Intersection of Two Linked Lists-এ সাধারণ ভুলগুলো কী?
Compare node identity, not values.