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.