Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 160 · Intersection

Intersection of Two Linked Lists

LeetCode 160 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Switch heads at the end; equal path lengths make them meet.

எளிதுHash TableLinked ListTwo Pointers
LeetCode இல் திற ↗

நான் 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. 1

    p1 = headA, p2 = headB.

  2. 2

    Step both; when one reaches the end, jump to the other list's head.

  3. 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 p1
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Intersection 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.