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.