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.